Inserting new attribute to a document using MongoDB ( Python )
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)
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'supsert
argument, it tells mongo to not insert a new document when no match is foundtrue
it'smulti
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/
db.collection.update({'_id' : ObjectId(...)},
{'$set' : {'create_time' : datetime(..) }})