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!

Asked By: DjangoRocks

||

Answers:

You can update the document using $set.

http://www.mongodb.org/display/DOCS/Updating

Or you can get the document, edit it (using python code) and save it back.

Answered By: Scott Hernandez
db.collection.update({'_id' : ObjectId(...)}, 
                     {'$set' : {'create_time' : datetime(..) }})
Answered By: Andreas Jung

if by any means, the update you were interested on, is solely for the created or updated date-time, you could just add this property when creating your model

{
    timestamps: true
}

that will add two properties updatedAt and createdAt
and mongodb will maintain them( created and update time) automatically for you.

Answered By: Xsmael

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/

Answered By: Taha EL BOUFFI

To add to Taha’s answer you can insert datetime attributes using currentDate:

db.getCollection("collection-name").update( 
{}, 
{
    $currentDate: {
        "date-field-name": { $type: "date" } // you can also use "timestamp" here
     }
}, 
false, true)

or to set a specific date you can use:

db.getCollection("collection-name").update( 
{}, 
{
    $set: {
        "date-field-name": ISODate("2020-01-23T04:05:06.007Z")
     }
}, 
false, true)
Answered By: TreeAndLeaf
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.