Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append existing array in existing collection in mongodb using java with new values

I have a mongo collection like:

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

    ]
}

I am using mongodb java 3.0 driver and trying to match and update. For eg: I am trying to match on entityId if it found then add the new nameIdentity.

Second time when I pass

{
    "fName": "123",
    "lName": "456",
    "dob": "00",
    "address": "789"
}

For my entityId: 12 if it matches then my new collection should like this:

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

I want to add it in the same matched object or collection. But its replacing the previous array and adding new like this:

{
    "_id": ObjectId("55cad746aed75601b4822cc9"),
    "entityId": "12",
    "entityType": "a",
    "nameIdentity": [

    {
        "fName": "123",
        "lName": "456",
        "dob": "00",
        "address": "789"
    }
    ]
}

When entity id is matched I want everything to be added not updated. The code I tried is :

mongoDatabase.getCollection("entity").findOneAndUpdate(
    updateDocument, new Document("$set",entityDocument));

I tried with $push and $set. Its creating a new nameIdentity Array. But I want to add in same matched nameIdentity array. Any suggestions where am I going wrong ?

like image 860
Shaik Mujahid Ali Avatar asked Aug 12 '15 05:08

Shaik Mujahid Ali


People also ask

How do I append to an array in MongoDB?

If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.

How do I update an array in MongoDB?

You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.

How do I update a nested array in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.


2 Answers

You should use $push like following:

db.collection.update({
    "entityId": "12"
}, {
    $push: {
    "nameIdentity": {
        "fName": "123",
        "lName": "456",
        "dob": "00",
        "address": "789"
    }
    }
})

Its equivalent query using mongo java driver is something like (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"))));

If you want to update many documents then use updateMany instead of updateOne by passing required params.

like image 129
Vishwas Avatar answered Oct 18 '22 08:10

Vishwas


You basically want to $push and add to the named array entry here. But for .findOneAndUpdate() you also need to set the ReturnDocument type in order to receive the result.

Otherwise the "original" document is returned, just as it is for all drivers.

    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());
like image 39
Blakes Seven Avatar answered Oct 18 '22 10:10

Blakes Seven