Mongodb Insert If Id Doesnt Exist in Array,Else Increment Field

#1

Hi guys i need some help with mongodb

This is my farms collections document.

{
    "_id" : ObjectId("513c7db4c079dc17dc75fc26"),
    "ownerId" : "J8MpsWChPQdET6jwQ",
    "level" : 1,
    "seeds" : [ 
        {
            "_id" : ObjectId("513c7db4c079dc17dc75fc26"),
            "count" : 10
        }
    ]
}

As you see there is a seeds array.What i am trying to do is check seeds array,if it has the object with given ObjectId,then increment count else Insert a new Object with Id and count 1

How do i do this ?

#2
const item = Collection.update({'_id': my_id, 'seeds._id': {$not: other_id } },  {$push: {seeds: {_id: other_id, count: 1} } });
if (!item) {
   Collection.update({'_id': my_id },
   {$inc: {'seeds.$[elem].count': 1} }
   {
     multi: true,
     arrayFilters: [ { 'elem._id': other_id } ]
   });
}

I would sort of start with something like this, not sure if you can do it in one operation, and check the response on item on update and non-update, not sure if that if statement is correct.

Again, not tested, its a start. see:
https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/

1 Like
#3

Thanks i solved it somehow