How to add an existing array to an 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 example: I try to match on entityId if it finds, then add a new nameIdentity .

The second time I go through

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

For my entityId: 12 , if it matches, my new collection should look 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 to the same consistent object or collection. But its replacing the previous array and adding a new type:

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

When the object identifier is matched, I want everything to be added not to be updated. The code I tried is:

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

I tried with $push and $set . Creates a new nameIdentity array. But I want to add the same nameIdentity array. Any suggestions I'm wrong about?

+5
source share
2 answers

You should use $ push as below:

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

His equivalent query using the mongo java driver is something like (verified) :

 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, use updateMany instead of updateOne , passing the necessary parameters.

+4
source

You basically want $push and add this entry here. But for .findOneAndUpdate() you also need to set ReturnDocument to get the result.

Otherwise, the "original" document is returned, as 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()); 
+1
source

All Articles