user1532669
user1532669

Reputation: 2378

How do I set and increment values in a collection with one query?

This should be a simple update query.

How can I update a collection so that I can set a=1 and increment b by one WHERE mystring=thestring?

I would think it would look something like this:

myCollection.update({  myString: thestring},
                              {$set: {a: 1},
                               $inc: {b: 1}
                           });

The above only sets a=1, b is not incremented so its not quite working properly. I've tried changing braces around but so far no luck.

Any ideas?

Upvotes: 1

Views: 189

Answers (1)

saimeunt
saimeunt

Reputation: 22696

Try this code in your browser console which is working for me :

MyCollection=new Mongo.Collection(null);

MyCollection.insert({
  myString:"thestring",
  a:2,
  b:4
});

MyCollection.update({
  myString:"thestring"
},{
  $set:{
    a:1
  },
  $inc:{
    b:1
  }
});

MyCollection.findOne();

Object {_id: "5JMPCqSwf7jmz9Z5H", myString: "thestring", a: 1, b: 5}

My guess is that you haven't quoted the string you are testing against. (myString: thestring)

Upvotes: 1

Related Questions