如何使用具有新值的java在mongodb中将现有数组附加到现有集合中

2022-09-04 03:09:42

我有一个mongo集合,如:

{
    "_id": ObjectId("55cad746aed75601b4822cc9"),
    "entityId": "12",
    "entityType": "a",
    "nameIdentity": [{
        "fName": "abc",
        "lName": "def",
        "dob": "00",
        "address": "xyz"
    },

    ]
}

我正在使用驱动程序,并尝试匹配和更新。例如:我正在尝试匹配,如果它找到,然后添加新的.mongodb java 3.0entityIdnameIdentity

第二次通过

{
    "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$setnameIdentitynameIdentity


答案 1

您应该使用如下所示的$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


答案 2

您基本上希望$push并添加到此处的命名数组条目中。但是对于 .findOneAndUpdate(),您还需要设置 ReturnDocument 类型才能接收结果。

否则,将返回“原始”文档,就像所有驱动程序一样。

    Document entityDocument = new Document();
    entityDocument.append("fname","123");
    entityDocument.append("lname","456");
    entityDocument.append("dob","00");
    entityDocument.append("address","789")

    Document doc = mongoDatabase.getCollection("entity").findOneAndUpdate(
            new Document("entityId", 12),
            new Document("$push", new Document("nameIdentity", entityDocument)),
            new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)
    );

    System.out.println(doc.toJson());