Ability to update nested field based on keys and upsert only document in nested field

Hi experts

I have a collection, where I need to upsert only on nested array and not on the document

db.nesteddemo.insertOne({name:“toplevel”,nested:[{id:1,val:“1”,val2:“2”}]})

db.nesteddemo.findOneAndUpdate({_id:ObjectId(“62a6a45bce71e57502b28344”)},{$addToSet:{nested:{id:2,val:2,val2:“2”}}})

db.nesteddemo.updateOne(
{_id:ObjectId(“62a6a45bce71e57502b28344”)},
{ $set: { “nested.$[elem].val” : -1 } },
{ arrayFilters: [ { “elem.id”: 3} ],upsert:true }
)
the above are not working
here if I want to conditionally perform upsert operation on nested field “nested” based on nested.id field

does mongodb support this operation ?

MongoDB does. Your data does not. You do not have a nested object with id:3.

yes steve, I am looking for an upsert , if the nested doc doesnt exists it should add ,if nested doc exists it should update

The arrayFilters is to match existing data you want to update.

To implement your use-case you have to use $push or $addToSet and add something like
"nested.id" : { "$ne" : 3 } in the query argument.

Steve, this will work for new inserts , but if the the document with id 3 exists, we may need to update the nested document, I am looking to see if I can acheive both in a single statment

I have to clue on how to do that easily.

But I would experiment with something like:

  1. using a { $set : { nested : { $cond : … } }
  2. the condition would use $elemMatch to test if id:3 is present
  3. if id:3 is present, use $map doing nothing to element where id is not 3, and $mergeObject when id:3
    3 if id:3 is not present, use $concatArray (may be $push but not sure), the old nested and one with id:3 element in it.