我有一个 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 驱动程序的等效查询类似于 (tested) :
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
。
关于java - 如何使用具有新值的java将现有数组附加到mongodb中的现有集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31956696/