Sandra Schlichting
Sandra Schlichting

Reputation: 25986

Search and replace in Mongo commandline

I can find all the first_name values by

> db.users.find().forEach( function(myDoc) { print( "first_name: " + myDoc.first_name ); } );
first_name: test1
first_name: test2
first_name: test3
first_name: test4
> 

but when I try and change them all to testing, then I get

> db.users.find().forEach( function(myDoc) { $set: {myDoc.first_name: "testing"};  } );
2018-06-27T16:58:54.268+0200 E QUERY    SyntaxError: Unexpected token :
> 

Question

Can anyone see why it doesn't replace all the first_name values to testing?

Upvotes: 0

Views: 29

Answers (1)

mickl
mickl

Reputation: 49945

The problem with your code is that $set can be used only inside update statements since it is a field update operator. So your code can be changed to:

db.users.find().forEach( function(myDoc) { db.users.update({_id: myDoc._id}, { $set: { first_name: "testing"} } ) ;  } );

Which can be achieved without fetching all documents:

db.users.update({}, { $set: { first_name: "testing3"} }, { multi: true } )

or if you want to modify document inside forEach then you can use .save() method in Mongo shell like:

db.users.find().forEach( function(myDoc) { myDoc.first_name = "testing2"; db.users.save(myDoc); } );

Upvotes: 2

Related Questions