Golang-Mongodb Insert element of array inside another array maintaining uniqueness of array

386 Views Asked by At

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.

0

There are 0 best solutions below