Updating an embedded subdocument in an array

367 views
Skip to first unread message

Kala N S

unread,
Jan 8, 2017, 2:31:45 PM1/8/17
to mongodb-user

I am pretty new to MongoDb. However i am trying to implement below functionality using java.


I Have a document as below. 


{

    "_id" : ObjectId("like-001"),

    "GroupID" : "1004",

    "likedBy" : [ 

        {

            "personId" : 123,

            "liked" : true

        },

 {

            "personId" : 167,

            "liked" : true

        },

 {

            "personId" : 467,

            "liked" : false

        }

    ],

    isdeleted:false

}




My functionality is, given a groupid, personId and Liked , find whether any document exist with given GroupId. If exist i should update that document with personId and Liked if the record not present, if person id also present I should not add the same person in array.


If the group id itself is not present I have to insert the entire document.


is there a way to do this with out making multiple calls to database. Also can this be done in bulk?




Wan Bachtiar

unread,
Jan 18, 2017, 2:04:00 AM1/18/17
to mongodb-user

I am pretty new to MongoDb. However i am trying to implement below functionality using java.

Hi Kala,

You can get started by following MongoDB Java Driver Tutorials. It provides examples of some frequently used operations.

is there a way to do this with out making multiple calls to database.

From what you have described, it is likely that it would require more than one query operation for your multiple conditional of actions. You may find update() with upsert option a useful resource.

Also can this be done in bulk?

See MongoDB Java Driver: Bulk Writes for bulk write commands for insert, update and delete.

If you have further questions, please provide the following:

  • MongoDB version
  • MongoDB Java Driver version
  • A snippet Java code of what you’ve tried, and what you would expect from the code.

Regards,

Wan.

Reply all
Reply to author
Forward
0 new messages