Search code examples
javascriptmongodbmongodb-querymongodb-shell

How to update a mongodb string field from command line?


I am trying to update a field from command line (NOT from mongo shell)

mongo mydb --eval "db.users.update({}, { $set : {  email : "email@email.com" } })"

results into

Fri Oct 24 12:23:46.102 JavaScript execution failed: SyntaxError: Unexpected token :

Again trying

mongo mydb --eval "db.users.update({}, { $set : {  email : \"email@email.com\" } })"

same results

Fri Oct 24 12:24:05.559 JavaScript execution failed: SyntaxError: Unexpected token :

Any help for the same ?


Solution

  • This is basically just quoting. The shell is generally more forgiving internally but does expect valid JSON otherwise:

    mongo mydb --eval "db.users.update({}, { '$set': {  'email' : 'email@email.com' } })"
    MongoDB shell version: 2.6.5
    connecting to: mydb
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    

    Actually, to play more nicely with other modifiers such a multi then reverse the type of quotes used:

    mongo mydb --eval 'db.users.update({}, { "$set": {  "email": "email@email.com" } },{ "multi": true })