我在mLab中有一个集合,需要添加一个JSON键值对。有哪些方法可以对集合中的所有文档执行此操作,无需手动编辑每个文档。
{
"_id": {
"$oid": "5b76acb78e7ea90016b46e6p"
},
"title": "document foo",
"new key": "new value",
}
您需要使用选项m=true
来更新所有符合条件的文档。而且,如果您基本上不通过标准,它将更新集合中的每个文档。
$.ajax( { url: 'https://api.mlab.com/api/1/databases/your-db/collections/your-collection?apiKey=yourAPIKey&m=true',
data: JSON.stringify( { "$set" : { "new key" : "new value" } } ),
type: "PUT",
contentType: "application/json" } );
使用Mongo shell解决了它:
try {db.collection.updateMany({},
{ $set: {"new key" : "new value"} });
} catch (e) {
print(e);
}