java - 只需要更新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"
}
}
]
}
解决方案
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": "印度” } })
推荐阅读
- javascript - 如何在js中从字符串转换为字节数组
- node.js - 如何使用 node js 从数字海洋中删除图像?
- javascript - 如何使用nodejs检查数组列表中存在的具有给定扩展名的文件
- odoo - 当库存数量小于零时,如何在网站上的产品上自动显示“缺货”?
- html - Kanna 在解析 HTML 时移除节点
- ios - 如何在 addSubview 中添加类 UIView
- list - 如何引用在类中创建的 List<> 对象?
- php - 路由 [LaravelInstaller::welcome] 未定义
- reactjs - 在 ReactJs 中使用 jsPDF 下载 PDF 后,字体系列不会在生产中呈现
- vb.net - cefsharp 在每个请求上更改 UserAgent