我是MOngoDB的新手(来自CouchDB),我在使用MonDB python驱动程序在MongDB中为我的文档添加新属性时遇到了问题.
例如,我有以下文件:
{
'_id':123456,
'text':"this is nice"
}
Run Code Online (Sandbox Code Playgroud)
我想插入一个新属性,例如:
{
'_id':123456,
'text':"this is nice",
'created_time':datetime.datetime.now()
}
Run Code Online (Sandbox Code Playgroud)
如何将created_time属性添加到我的文档中?
谢谢!
小智 56
db.collection.update({'_id' : ObjectId(...)},
{'$set' : {'create_time' : datetime(..) }})
Run Code Online (Sandbox Code Playgroud)
小智 11
要向MongoDB集合上的所有现有文档插入新属性,我们可以在mongo shell上执行以下方法:
db.collection.update(
{},
{'$set': {"new_attribute":"attribute_value"}},
false,
true
)
Run Code Online (Sandbox Code Playgroud)
{} 这是查询条件,在本例中,将新属性添加到所有记录中,我们传递了一个空对象 {}{'$set': {"new_attribute":"attribute_value"}}表示使用$set运算符,在我们的记录上插入一个"new_attribute"具有此值的新密钥"attribute_value"false它的upsert参数,它告诉mongo在找不到匹配项时不要插入新文档true它的multi参数,它告诉mongo更新满足查询条件的多个文档要查找更多详细信息,请检查:https : //docs.mongodb.com/manual/reference/method/db.collection.update/