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.

2
  • see this answer its very similar, i think you want if exists to update it, else push in the end Commented Apr 15, 2022 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? Commented May 25, 2022 at 7:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.