2017-09-01 236 views
1

我试图使用Rust更新MongoDB数据库集合中的字段。我用这个代码:使用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"); 
} 

这给了我一个错误说只更新与$运营商,经过一番搜索,似乎意味着我应该使用$set工作。我一直在尝试不同的版本,但只能得到不匹配的类型错误等。

coll.update_one({"DEVID": "1"},{$set:{"temp" => "5"}},None).expect("failed"); 

我哪里错了?

数据库看起来像这样。

db.DEVICES.find() 

{ "_id" : ObjectId("59a7bb747a1a650f1814ef85"), "DEVID" : 1, "temp" : 0, 
"room_temp" : 0 } 

{ "_id" : ObjectId("59a7bb827a1a650f1814ef86"), "DEVID" : 2, "temp" : 0, 
"room_temp" : 0 } 

回答

1

你几乎在那里。对我来说,下面的编译和运行,当我尝试你的榜样(提示:您还没有加括号“$集”):

#[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(); 
} 

另一个忠告:使用unwrap而不是expect可能会给你更精确错误。

至于使用mongodb库,我已经远离,因为作者明确指出它的文档中的not production ready甚至update_one示例已被破坏。

相反,我用wrapper over the battle-tested C-library,结果很好。

+0

我试图用引号和其他一些东西括起来,它仍然不会工作,我开始认为它刚刚坏了。我开始尝试使用C封装,但他们没有任何例子,我仍然很新。 – dmnte

+0

我上面粘贴的代码编译并运行在Rustc 1.19上。 – PureW

+0

代码也为我编译和运行,但并没有改变字段,在代码即时通讯使用“1”,但在数据库它只是1.这是否重要? – dmnte