0

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

pkpk
  • 641
  • 1
  • 7
  • 18
  • Possible duplicate https://stackoverflow.com/questions/10522347/mongodb-update-objects-in-a-documents-array-nested-updating – Molda Dec 21 '17 at 17:27
  • Possible duplicate of [MongoDB - Update objects in a document's array (nested updating)](https://stackoverflow.com/questions/10522347/mongodb-update-objects-in-a-documents-array-nested-updating) – s7vr Dec 21 '17 at 17:28
  • It seems not possible to do in a single query, but these answers are from almost 6 years ago. Just want to make sure it is still the case. – pkpk Dec 21 '17 at 18:40

0 Answers0