Updating MongoDB object field

database, mongodb

Solution

First of all if you are trying to update the role field of the profile subdocument your syntax is off. It should be:

db.users.update({_id:"2xnoy3jqcHCaFp7Br"}, {$set: { "profile.role":"admin"}})

Otherwise you will just delete all the other fields of the document.

Regarding the error message, that normally only occurs when you run update with a single argument (the query) without the fields to update. Are you sure you are calling it as documented in your question?

Regardless I would highly advise you to review MongoDB documentation for updates:

http://docs.mongodb.org/manual/tutorial/modify-documents/

Problem

I have searched and tried many answers but I can't seem to get this working. I have a user in MongoDB (db.users...) and I'm trying to update a field titled 'role' in one particular document. If I perform a : ``` db.users.find(); ``` I get: ``` { "_id" : "fDx2g34G8vxsDu3vf", "createdAt" : ISODate("2014-06-03T16:31:47.382Z"), "emails" : [ { "address" : "andrewmlarking@gmail.com", "verified" : false } ], "profile" : { "name" : "Admin", "role" : "user", "division" : "0", "enrolled" : "false" }, "services" : { "password" : { "srp" : { "identity" "dEad06c_5mjzsprUzgRyh6tB66OiaybdLzbnxFzO1xh", "salt" : "zqWsh etc etc ``` Which is fine, if I then perform a: ``` db.users.update({_id:"2xnoy3jqcHCaFp7Br"}, { role:"admin"}); ``` I get a: assert failed : need an object Error: Printing Stack Trace at printStackTrace (src/mongo/shell/utils.js:37:15) at doassert (src/mongo/shell/assert.js:6:5) at assert (src/mongo/shell/assert.js:14:5) at DBCollection.update (src/mongo/shell/collection.js:220:5) at (shell):1:10 Any ideas? Thanks.

Original source