I am new to Mongodb and Mongoengine. And I am wondering if there is a way to bulk update MongoDB fields with a json script, for instance:
我是Mongodb和Mongoengine的新手。我想知道是否有办法用json脚本批量更新MongoDB字段,例如:
jsonData = {'name': 'Stak', 'password':'oVeRfLoW'}
User.objects.get(username='u_name').update(jsonData)
Thanks for your answers!
谢谢你的回答!
1 个解决方案
#1
Mongodb's built-in update function, db.collection.update() is very customizable, has options for updating multiple documents at once and doesn't require getting anything beforehand.
Mongodb的内置更新函数db.collection.update()是非常可定制的,具有一次更新多个文档的选项,并且不需要事先获取任何内容。
You can use it like so:
您可以像这样使用它:
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
So in this case:
所以在这种情况下:
db.collection.update(
{username:'u_name'}, //1
{$set:jsonData}, // 2
{
multi: true, // 3
}
)
(
- the query searches for documents that have
- $set is IMPORTANT! If you do not use $set, your entire document will be erased and updated to a document containing only your new values. (it will delete all the other fields)
- Update multiple documents at once.
查询搜索具有的文档
$ set非常重要!如果您不使用$ set,则整个文档将被删除并更新为仅包含新值的文档。 (它将删除所有其他字段)
一次更新多个文档。
Keep in mind this is a guideline and you'll have to modify the above code a bit.
请记住,这是一个指南,你必须稍微修改上面的代码。
#1
Mongodb's built-in update function, db.collection.update() is very customizable, has options for updating multiple documents at once and doesn't require getting anything beforehand.
Mongodb的内置更新函数db.collection.update()是非常可定制的,具有一次更新多个文档的选项,并且不需要事先获取任何内容。
You can use it like so:
您可以像这样使用它:
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
So in this case:
所以在这种情况下:
db.collection.update(
{username:'u_name'}, //1
{$set:jsonData}, // 2
{
multi: true, // 3
}
)
(
- the query searches for documents that have
- $set is IMPORTANT! If you do not use $set, your entire document will be erased and updated to a document containing only your new values. (it will delete all the other fields)
- Update multiple documents at once.
查询搜索具有的文档
$ set非常重要!如果您不使用$ set,则整个文档将被删除并更新为仅包含新值的文档。 (它将删除所有其他字段)
一次更新多个文档。
Keep in mind this is a guideline and you'll have to modify the above code a bit.
请记住,这是一个指南,你必须稍微修改上面的代码。