只需要更新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"

            }

        }

    ]

}


牧羊人nacy
浏览 116回答 3
3回答

杨魅力

我是怎么做的。我制作了一个文档,在其中添加了我想要更新的所需数据。说Document valueDocument = new Document();valueDocument.put("InitialValue", USA);BasicDBObject query = new BasicDBObject();query.put("Attributes", att);BasicDBObject data = new BasicDBObject();data.put("Attributes.$.updatedvalue" + qCLevel, valueDocument);BasicDBObject command = new BasicDBObject();command.put("$set", data);collection.updateOne(query, command);它会在正确的位置插入数据。

手掌心

试试这个db.collection.updateMany(&nbsp;{ "Attributes.actualValue.initialValue": "USA" },&nbsp;{ $set: { "Attributes.$.updatedvalue" : {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "initialValue" : "USA",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "changedValue" : "Europe"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} } })

弑天下

db.collection.findOneAndUpdate({ "Attributes.actualValue.initialValue": "USA" },&nbsp;&nbsp; { $set: { "Attributes.$.updatedvalue.initialValue": "USA",&nbsp; &nbsp; &nbsp; "Attributes.$.updatedvalue.changedValue": "Europe" } })db.collection.findOneAndUpdate({ "Attributes.actualValue.initialValue": "USA" }, { $set: { "Attributes.$.updatedvalue.initialValue": "India", "Attributes.$.updatedvalue.changedValue": "印度” } })
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java