Right i understand that need do 3 query for simple action ‘savebook’?
Take into that the method can call many times. For clear collection and for exists document.
function savebook(mybookWithId55){
// 1. create document if not exists
db.update( { userId: 1 }, { $setOnInsert: { books: [] } }, upsert: true )
// 2. if not exists book in nested array -> push
let dummy= { bookId: 55 };
db.update( { userId: 1, books.bookId: { $ne: 55 } } , { $push: { books: dummy } } )
// 3. update book with full fields
db.update( { userId: 1} , { $set: { books.$[i]: mybookWithId55} }, { arrayFilters: [ { i.bookId: 55} })
}
So in my opnion this is not a simplistic update and it involves some business logic in it. You can achieve it via 2 commands that will eventually update will run only when required: