首页 > 解决方案 > 只需要更新java中mongo数组中的特定元素

问题描述

我想用过滤器更新 mongo 数组中的特定元素。

我已经尝试过使用BasicDBObject,但不能使用过滤器,因为我有类型的集合MongoCollection

MongoCollection collection = db.getCollection(tnId);

甚至尝试过:

FindIterable<Document> document = collection.find(new BasicDBObject("DocumentName", documentName)                       .append("Attributes.name", "Party 1" ).append("Attributes.value", 12)                   .append("Attributes.actualValue.initialValue", USA));

但在这种情况下,我得到的是整个记录,而且我必须再次遍历每个属性。

mongo = new MongoClient("localhost", 27017);
MongoDatabase db = mongo.getDatabase(companyName);
MongoCollection collection = db.getCollection(tnId);

我传递的实际数据是

{
    "DocumentName" : "doc1",
    "Attributes" : [ 
        {
            "name" : "Party 1",
            "value" : 12,
            "actualValue" : {
                "initialValue" : "USA"
            }
        }, 
        {
            "name" : "Party 1",
            "value" : 16,
            "actualValue" : {
                "initialValue" : "SYSTEM"
            }
        }
    ]
}

我想搜索actualValue为“USA”且属性值为12的属性,更新后的数据应如下所示

{
    "DocumentName" : "doc1",
    "Attributes" : [ 
        {
            "name" : "Party 1",
            "value" : 12,
            "actualValue" : {
                "initialValue" : "USA"
            },
            "updatedvalue" : {
                "initialValue" : "USA",
                "changedValue" : "Europe"
             }

        }, 
        {
            "name" : "Party 1",
            "value" : 16,
            "actualValue" : {
                "initialValue" : "SYSTEM"
            }
        }
    ]
}

标签: javaarraysmongodbfilter

解决方案


db.collection.findOneAndUpdate({ "Attributes.actualValue.initialValue": "USA" }, 
  { $set: { "Attributes.$.updatedvalue.initialValue": "USA",      "Attributes.$.updatedvalue.changedValue": "Europe" } })

db.collection.findOneAndUpdate({ "Attributes.actualValue.initialValue": "USA" }, { $set: { "Attributes.$.updatedvalue.initialValue": "India", "Attributes.$.updatedvalue.changedValue": "印度” } })


推荐阅读