2

Currently I am learning learn to create restful api with golang and mongodb. I am using mongo-go-driver. I got stuck at this.

Let's say I have a collection that has document entries with the structure like below.

{
    "_id" : "6257067a54d34221dcdef56e"
    "name" : "Bob",
    "booksCollection" : [
         {"bookId" : 10, "addedOn" : "date when added"},
         {"bookId" : 15, "addedOn" : "date when added"},
         {"bookId" : 20, "addedOn" : "date when added"},
    ]
}

Now I want to insert some more books inside "booksCollection". I have an array as below which I want to insert.

[{"bookId" : 10, "addedOn" : "currentDate"}, {"bookId" : 25, "addedOn" : "currentDate"}]

How can I added these books inside "booksCollection" which maintaining uniqueness of "booksCollection". Below should be the final result.

{
    "_id" : "6257067a54d34221dcdef56e"
    "name" : "Bob",
    "booksCollection" : [
         {"bookId" : 10, "addedOn" : "date when added"},
         {"bookId" : 15, "addedOn" : "date when added"},
         {"bookId" : 20, "addedOn" : "date when added"},
         {"bookId" : 25, "addedOn" : "date when added"},
    ]
}

Sorry for the bad English.

  • see this [answer](https://stackoverflow.com/questions/71887341/push-an-array-element-if-certain-element-not-exists-or-update-in-mongodb) its very similar, i think you want if exists to update it, else push in the end – Takis Apr 15 '22 at 19:53
  • 1
    Sorry for the late response @Takis , Yes you are right but I have array of elements which I want to insert. I don't want to insert them one by one. Is there any way by which I can insert all elements by a single query? – Vishal Kumar Mahto May 25 '22 at 07:03

0 Answers0