我有一个mongo集合,例如:
{
"_id": ObjectId("55cad746aed75601b4822cc9"),
"entityId": "12",
"entityType": "a",
"nameIdentity": [{
"fName": "abc",
"lName": "def",
"dob": "00",
"address": "xyz"
},
]
}
我正在使用mongodb java 3.0
驱动程序并尝试匹配和更新。例如:我正在尝试entityId
找到它,然后添加新的nameIdentity
。
我第二次通过
{
"fName": "123",
"lName": "456",
"dob": "00",
"address": "789"
}
对于我来说,entityId: 12
如果匹配,那么我的新收藏应该像这样:
{
"_id": ObjectId("55cad746aed75601b4822cc9"),
"entityId": "12",
"entityType": "a",
"nameIdentity": [{
"fName": "abc",
"lName": "def",
"dob": "00",
"address": "xyz"
}, {
"fName": "123",
"lName": "456",
"dob": "00",
"address": "789"
}]
}
我想将其添加到相同的匹配对象或集合中。但是它替换了以前的数组并添加了新的数组,如下所示:
{
"_id": ObjectId("55cad746aed75601b4822cc9"),
"entityId": "12",
"entityType": "a",
"nameIdentity": [
{
"fName": "123",
"lName": "456",
"dob": "00",
"address": "789"
}
]
}
当实体ID匹配时,我希望添加的所有内容都不会更新。我试过的代码是:
mongoDatabase.getCollection("entity").findOneAndUpdate(
updateDocument, new Document("$set",entityDocument));
我尝试了$push
和$set
。它创建了一个新的nameIdentity
数组。但是我想添加相同的匹配nameIdentity
数组。有什么建议我要去哪里错吗?
您应该像下面这样使用$ push:
db.collection.update({
"entityId": "12"
}, {
$push: {
"nameIdentity": {
"fName": "123",
"lName": "456",
"dob": "00",
"address": "789"
}
}
})
使用mongo java驱动程序的等效查询类似于(已测试):
db.getCollection("entity").updateOne(new Document("entityId", "12"),
new Document("$push", new Document("nameIdentity", new Document("fName", "123").append("lName", "456")
.append("dob", "00").append("address", "789"))));
如果要更新许多文档,请使用updateMany而不是updateOne
传递必需的参数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句