1

From the documentation I read you can do this:

 db.people.update( { name:"Joe" }, { $set: { n : 1 } } );

( http://www.mongodb.org/display/DOCS/Updating )

Now I would like to set it to a dynamic value like a counter or expression:

var i = 0;
db.people.update( { name:"Joe" }, { $set: { n : $i++ } } );

db.people.update( { name:"Joe" }, { $set: { n : ${new Date()} } } );

Is this possible ?

I would also accept any solution that does not need to modify and save the full document.

2
  • Do you know what $inc does? the examples you gave doesn't make much/any sense Commented Sep 8, 2011 at 16:38
  • Sorry I ment set. I correct my mistake, thanks ! Commented Sep 8, 2011 at 17:00

1 Answer 1

1

mongo is an extended javascript shell with mongodb support, so you can do anything that you can do with plain javascript:

var i = 0;
db.people.update( { name:"Joe" }, { $set: { n : i++ } } );

and

db.people.update( { name:"Joe" }, { $set: { n : new Date() } } );

Update

ah so.. that's not going to work. You have to update each document invidually! JS is executed before you pass that query to the database. Effectly you're doing the following:

db.foo.update( {}, { $set: { n : 0 } }, false, true ); # i was zero here
i++;

As I said, you have to update each document individually, but you can execute the whole thing on server-side with db.eval( ) to speed up things a little bit;)

Sign up to request clarification or add additional context in comments.

4 Comments

I tried your suggestion but it seems that i++ is only evaluated once thus all documents get the same value (1). I guess it makes sense. But I am still looking for a way to assign an expression that is evaluated each time.
no it's evaluated each time. you're doing something wrong, show the code. maybe you're storing the result (object) and hoping it will evaluate again?
I tried it again, see new answer ( I couldn't get it to properly format as a comment... )
yes, I did this in the end: db.eval(function() {db.people.find().forEach( function(obj) {obj.n = new Date();db.people.save(obj);} );}); Thanks for all your help !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.