Trying to figure out if I can do this in a single update statement. I'm using nodejs.
I have a collection "data" with following structure
_id: id
books: [{
bookId: id,
count: count
}]
Basically 2 top level fields, first _id and second array of objects called books. This object has 2 fields bookid and the count.
so if my data is something like this
{ _id: 1, books: [{bookId: 100, count: 1}, {bookId: 101, count: 2}] }
{ _id: 2, books: [{bookId: 100, count: 3}, {bookId: 101, count: 4}] }
{ _id: 3, books: [{bookId: 103, count: 3}, {bookId: 101, count: 4}] }
I want to query based on top level field _id and then I want to update books array. I also have bookId with me, so if array has this bookId, then count should be increased by 1. If book array does not have this bookId, then a new object with count set to 1 should be added.
so for example for _id: 1 and bookId: 101, update should result in
{ _id: 1, books: [{bookId: 100, count: 1}, {bookId: 101, count: 3}] }
and for _id:1 and bookId: 103, update should result in
{ _id: 1, books: [{bookId: 100, count: 1}, {bookId: 101, count: 3}, {bookId: 103, count: 1} ] }
Remember I'm trying to do this in a single statement.
Thanks