0

I have a client document that contains contacts as an array of sub-documents.

When I send the client document to the DB it should behave in the following manner:

If the document doesn't exist, create the document along with all sub documents.

If the document does exist, then add missing contacts (multiple) to array of sub documents.

After doing some research I found something that matches what I'd like to do but it seems to work only with a single additional sub document instead of an array of sub documents.

I am also having a really hard time recreating this using the mongodb c# driver.

Does anyone know if its possible to do this in one query?

This is what I have found so far:

db.clients.update({$and:[{'clientName':'apple'},{'contacts.firstName': {$ne: 'nick'}},{'contacts.lastName': {$ne: 'white'}}]}, 
              {$set:{'clientName':'apple'}, $push: {contacts: {'firstName': 'nick', 'lastName':'white'}}},
              {upsert: true });
Soulfly
  • 214
  • 1
  • 10
  • You cannot mix "upsert" with a conditional `$push` to an array in a single statement. The linked answers explain why, and that you should in modern terms use `bulkWrite()` for the ***three** separate* operations that are actually needed for this. – Neil Lunn Mar 15 '19 at 01:34
  • So the "duplicate" questions are all related to MongoDB and not to c# at all. Mind not marking this question as a duplicate as I'd like to get some c# answers? – Soulfly Mar 15 '19 at 02:10
  • I think you need to understand that this is not a **single operation** as per your expected "snippet" of code. Language makes no difference whatsoever as to "how things actually work". – Neil Lunn Mar 15 '19 at 03:09

0 Answers0