Update (increment) array's object field or create (if not exists) whole document - MongoDb

Viewed 56

I'd like to increment some field in nested array or if document not exists, or object in array - create them.

Example of existing filled document:

{
  _id: "some_id_1",
   my_objects: [
   {
     objectId: "abc",
     fieldA: -5, 
     fieldB: 44
   },
   {
     objectId: "123",
     fieldA: -6, 
     fieldB: 88
   }
  ]
}

To increment fieldA in array's object with id abc I can write query:

colection.updateOne(
{$and:[
   {$eq:[_id, "some_id_1"]}, 
   {$eq:[objectId, "abc"]}
]},
   {$inc:{"my_objects.$.fieldA":1}}
)

and it works.

The problem is when this collection is empty or my_objects is empty. If document doesn't exist I'd like to create the document with object in array . Or if document exists but array my_objects is empty I'd like to add object with fieldA to array.


///documnet after single update query. Is it possible?
{
   _id: "some_id_1",
   my_objects: [
     {
       objectId: "abc",
       fieldA: 1, 
     }
  ]
}
0 Answers
Related