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?

Answers


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)


Need Your Help

Is boost::container::vector faster than std::vector? Why?

c++ boost vector std

I did a interesting test on boost vector and std vector as the following

Memoization or Tabulation approach for Dynamic programming

c algorithm recursion time-complexity dynamic-programming

There are many problems that can be solved using Dynamic programming e.g. Longest increasing subsequence. This problem can be solved by using 2 approaches

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.