我正在尝试使用 Rust 更新 MongoDB 数据库集合中的字段。我正在使用这段代码:
extern crate mongodb;
use mongodb::{Client, ThreadedClient};
use mongodb::db::ThreadedDatabase;
fn main() {
let client = Client::connect("ipaddress", 27017);
let coll = client.db("DEV").collection("DEV");
let film_a = doc!{"DEVID"=>"1"};
let filter = film_a.clone();
let update = doc!{"temp"=>"5"};
coll.update_one(filter, update, None).expect("failed");
}
Run Code Online (Sandbox Code Playgroud)
这给了我一个错误,说 update 仅适用于$运算符,经过一番搜索后似乎意味着我应该使用$set. 我一直在尝试不同的版本,但只会出现类型不匹配的错误等。
coll.update_one({"DEVID": "1"},{$set:{"temp" => "5"}},None).expect("failed");
Run Code Online (Sandbox Code Playgroud)
我哪里错了?
数据库看起来像这样。
extern crate mongodb;
use mongodb::{Client, ThreadedClient};
use mongodb::db::ThreadedDatabase;
fn main() {
let client = Client::connect("ipaddress", 27017);
let coll = client.db("DEV").collection("DEV");
let film_a = doc!{"DEVID"=>"1"};
let filter = film_a.clone();
let update = doc!{"temp"=>"5"};
coll.update_one(filter, update, None).expect("failed");
}
Run Code Online (Sandbox Code Playgroud)
如果有人正在寻找更新版本驱动程序的答案,这里它基于 @PureW 在异步版本中的答案:
use mongodb::{Client, ThreadedClient, bson::doc};
use mongodb::db::ThreadedDatabase;
async fn main() {
let client = Client::connect("localhost", 27017).unwrap();
let coll = client.db("tmp").collection("tmp");
let filter = doc!{"DEVID":"1"};
let update = doc!{"$set": {"temp":"5"}};
coll.update_one(filter, update, None).await.unwrap();
}
Run Code Online (Sandbox Code Playgroud)
你已经差不多了。当我尝试您的示例时,以下内容将为我编译并运行(提示:您没有将“$set”括在引号中):
#[macro_use(bson, doc)]
extern crate bson;
extern crate mongodb;
use mongodb::{Client, ThreadedClient};
use mongodb::db::ThreadedDatabase;
fn main() {
let client = Client::connect("localhost", 27017).unwrap();
let coll = client.db("tmp").collection("tmp");
let filter = doc!{"DEVID"=>"1"};
let update = doc!{"$set" => {"temp"=>"5"}};
coll.update_one(filter, update, None).unwrap();
}
Run Code Online (Sandbox Code Playgroud)
另一条建议:使用unwrap而不可能expect会给你带来更精确的错误。
至于使用 mongodb-library,我已经远离它,因为作者明确表示它还没有准备好用于生产,甚至update_one他们文档中的示例也被破坏了。
相反,我在久经考验的 C 库上使用了包装器,并取得了良好的结果。