Inserting new attribute to a document using MongoDB ( Python )


I'm new with MOngoDB ( coming from CouchDB ) and I am having issues with adding new attributes to my documents in MongDB using the MonDB python driver.

For example, I have the following document:

'text':"this is nice"

And I want to insert a new attribute, for example:

'text':"this is nice",

How do I go about adding the created_time attribute to my document?


2/20/2011 9:25:14 AM

Accepted Answer

db.collection.update({'_id' : ObjectId(...)}, 
                     {'$set' : {'create_time' : datetime(..) }})
2/20/2011 4:24:24 PM

To insert a new attribute to all existing documents on a MongoDB collection, we can perform this method on our mongo shell:

    {'$set': {"new_attribute":"attribute_value"}}, 
  • {} it's the query criteria, in our case to add our new attribut to all our records, we pass an empty object {}
  • {'$set': {"new_attribute":"attribute_value"}} means that using $set operator, insert on our records a new key "new_attribute" that will have this value "attribute_value"
  • false it's upsert argument, it tells mongo to not insert a new document when no match is found
  • true it's multi argument, it tells mongo to update multiple documents that meet the query criteria

To find more details check:

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow