在java中只需要更新mongo数组中的特定元素
我想用过滤器更新mongo数组中的特定元素 我已经尝试过使用在java中只需要更新mongo数组中的特定元素,java,arrays,mongodb,filter,Java,Arrays,Mongodb,Filter,我想用过滤器更新mongo数组中的特定元素 我已经尝试过使用basicdboObject,但无法使用过滤器,因为我有类型为MongoCollection的集合 MongoCollection collection = db.getCollection(tnId); 甚至尝试过: FindIterable<Document> document = collection.find(new BasicDBObject("DocumentName", documentName)
basicdboObject
,但无法使用过滤器,因为我有类型为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));
我传递的实际数据是
{
"DocumentName" : "doc1",
"Attributes" : [
{
"name" : "Party 1",
"value" : 12,
"actualValue" : {
"initialValue" : "USA"
}
},
{
"name" : "Party 1",
"value" : 16,
"actualValue" : {
"initialValue" : "SYSTEM"
}
}
]
}
我想搜索属性,其中实际值是“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"
}
}
]
}
试试这个
db.collection.updateMany(
{ "Attributes.actualValue.initialValue": "USA" },
{ $set: { "Attributes.$.updatedvalue" : {
"initialValue" : "USA",
"changedValue" : "Europe"
} } }
)
db.collection.findOneAndUpdate({“Attributes.actualValue.initialValue”:“USA”},
{$set:{“Attributes.$.updatedvalue.initialValue”:“USA”,“Attributes.$.updatedvalue.changedValue”:“Europe”})
我是如何做到的。我制作了一个文档,在其中添加了我想要更新的所需数据
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);
它将在正确的位置插入数据。我希望根据名称、值和actualValue.initialValue全部3进行筛选。因为我的数据可以重复。一旦我得到数据,就只更新那个数据。我想要类似于
Bson updateDocument=newdocument(“$set”,d)的东西;collection.updateOne(过滤器,updateDocument)那么如何编写过滤器呢?
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);