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

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 ?

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

Thanks i solved it somehow

Could you say how you solved it?

If there are many farms with many seeds, the DB structure is not too efficient. You would rather keep a collection for seeds indexed by farmId and ownerId, beside the farms collection, something like below. MongoDB (and NoSQL) prefers, in your case, to keep two perspectives: farms and farm on the seeds in order to avail of the incredible query speeds of NoSQL.:

// Seeds collection:
{
  _id :.......,
 farmId: ......,
 ownerId: .....
}

In this way, your queries become really basic, incredibly fast and low-memory on the server-side.