dmnte
dmnte

Reputation: 155

Updating data in MongoDB with Rust

I'm trying to update a field in a collection of a MongoDB database using Rust. I was using this code:

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");
}

This gives me an error saying update only works with the $ operator, which after some searching seems to mean I should use $set. I've been trying different versions of this but only get mismatched type errors and such.

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

Where am I going wrong?

The DB looks like this.

db.DEVICES.find()

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

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

Upvotes: 6

Views: 5508

Answers (2)

moy2010
moy2010

Reputation: 900

If someone is looking for the answer for a newer version of the driver, here it is based on @PureW's answer in an async version:

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

Upvotes: 6

PureW
PureW

Reputation: 5095

You're pretty much there. The following compiles and runs for me when I try your example (hint: You haven't enclosed "$set" in quotes):

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

Another piece of advice: Using unwrap rather than expect might give you more precise errors.

As for using the mongodb-library, I've stayed away from that as the authors explicitly say it's not production ready and even the update_one example in their documentation is broken.

Instead I've used the wrapper over the battle-tested C-library with good results.

Upvotes: 4

Related Questions