【问题标题】:MongoDB: Update nested array fields in all documents in a collectionMongoDB:更新集合中所有文档中的嵌套数组字段
【发布时间】:2015-07-30 19:59:05
【问题描述】:

这是我的示例文档:

{
    "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.addresses 添加另一个键值对来更新我的集合中的所有文档。我该怎么做?我无法访问地址内的对象。

我想将此键值对添加到所有addresses:"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"
        }]
    }
}

【问题讨论】:

标签: javascript mongodb mongodb-query


【解决方案1】:

如果我了解您想要更新所有文档并将"country": "USA" 添加到customer.address 中的每个子文档。您可以使用Bulk() 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-20
    • 2017-04-28
    • 2023-04-03
    • 2018-12-08
    • 2021-12-31
    • 2012-03-25
    • 2021-07-24
    • 1970-01-01
    相关资源
    最近更新 更多