0

I am new to Mongodb and Mongoengine. And I am wondering if there is a way to bulk update MongoDB fields with a json script, for instance:

jsonData = {'name': 'Stak', 'password':'oVeRfLoW'}
User.objects.get(username='u_name').update(jsonData)

Thanks for your answers!

benjaminz
  • 3,118
  • 3
  • 35
  • 47

1 Answers1

0

Mongodb's built-in update function, db.collection.update() is very customizable, has options for updating multiple documents at once and doesn't require getting anything beforehand.

You can use it like so:

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

So in this case:

db.collection.update(
   {username:'u_name'}, //1
   {$set:jsonData}, // 2
   {
     multi: true, // 3
   }
)

(

  1. the query searches for documents that have
  2. $set is IMPORTANT! If you do not use $set, your entire document will be erased and updated to a document containing only your new values. (it will delete all the other fields)
  3. Update multiple documents at once.

Keep in mind this is a guideline and you'll have to modify the above code a bit.

Digits
  • 2,634
  • 2
  • 14
  • 23
  • Thank you! A follow up question: suppose I use the code you provided above, and I want to update a ListField like so: 'credentials': [ {'cid': 001, 'alias': 'blah'}, {'cid': 001, 'alias': 'blah'}]. And I want to update each 'alias' of these credentials to 'bah'. What should the query be? I tried using the {$set: {credentials: {$each: {'alias': 'bah'} } } } but it throws errors; – benjaminz May 11 '15 at 14:07
  • Not sure, that's a tough one. I'd look here http://stackoverflow.com/questions/4669178/how-to-update-multiple-array-elements-in-mongodb seems to have an answer that may work. The latest answer (march 1) is likely good. – Digits May 11 '15 at 16:05