Note: checking if the key books
exist or not, creating if not and than updating it.
I am using mongodb driver with nodejs.
In the db.collection('userData')
The document looks like this:
{
user_id: 'user1',
books: [{
id: 'book1',
title: 'this is book1'
},
{
id: 'book1',
title: 'this is book1'
}]
}
when inserting a new book entry, how to check if the array of books
exists in the document, if not then add a key books
in the document and then insert the book entry.
You have to do 2 separate queries,
Second option you can use update with aggregation pipeline starting from MongoDB 4.2,
$ifNull
check is field is null then return []$concatArrays
to concat currentbooks
with new book objectPlayground