问题描述
这是我的示例文档:
{
"isUpdated": false,
"isDeleted": false,
"customer": {
"name": "John Doe",
"address": [{
"houseNum": 5,
"streetName": "Example Avenue",
"postalCode": "90210"
}, {
"houseNum": 15,
"streetName": "Second Example Avenue",
"postalCode": "91210"
}]
}
}
我有几个类似的文件。
我想通过向所有customer.address
es添加另一个键值对来更新我的集合中的所有文档。
我该怎么做?
我无法访问地址内的对象。
我想将这个键值对添加到所有address
es: "country": "USA"
。
那么,现在该示例文档将如下所示:
{
"isUpdated": false,
"isDeleted": false,
"customer": {
"name": "John Doe",
"address": [{
"houseNum": 5,
"streetName": "Example Avenue",
"postalCode": "90210",
"country": "USA"
}, {
"houseNum": 15,
"streetName": "Second Example Avenue",
"postalCode": "91210",
"country": "USA"
}]
}
}
1楼
styvane
5
已采纳
2015-07-30 21:01:37
如果我了解您要更新所有文档并将"country": "USA"
到customer.address
中的每个子文档。
您可以使用 API执行此操作
var bulk = db.collection.initializeOrderedBulkOp();
var count = 0;
db.collection.find().forEach(function(doc){
var addr = doc["customer"]["address"];
for (var i = 0; i < addr.length; i++) {
bulk.find({
"_id": doc._id,
"customer.address": { "$elemMatch": {
"houseNum": addr[i][ "houseNum" ],
"streetName": addr[i][ "streetName" ]}}
}).update({
"$set": { "customer.address.$.country": "USA" }
})}
count++;
if ( count % 1000 == 0 ) {
// Execute per 1000 operations and re-init.
bulk.execute();
bulk = db.collection.initializeOrderedBulkOp();
}
})
// Clean up queues
if ( count % 1000 != 0 ){
bulk.execute();
}