Inserting new attribute to a document using MongoDB ( Python )


Question

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:

{
'_id':123456,
'text':"this is nice"
}

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

{
'_id':123456,
'text':"this is nice",
'created_time':datetime.datetime.now()
}

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

Thanks!

1
30
2/20/2011 9:25:14 AM

Accepted Answer

db.collection.update({'_id' : ObjectId(...)}, 
                     {'$set' : {'create_time' : datetime(..) }})
54
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:

db.collection.update( 
    {}, 
    {'$set': {"new_attribute":"attribute_value"}}, 
    false, 
    true
)
  • {} 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: https://docs.mongodb.com/manual/reference/method/db.collection.update/


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