开发者

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:

{
'_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!


db.collection.update({'_id' : ObjectId(...)}, 
                     {'$set' : {'create_time' : datetime(..) }})


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/


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.


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜