I have a users collection in my mongoDB. Now I want to update favorites array only if its size is less than 50.

  "_id": 'mongo_id',
  "name": "test user",
  "email": "[email protected]",
  "full_name": "",
  "first_name": "",
  "last_name": "",
  "mobile_number": "",
  "email_id": "[email protected]",
  "profile_photo": "",
  "roles": [],
  "favorites": [
    { obj1 }, { obj2 }, { obj3 }, { obj4 }, 
  ],
}```

Currently I'm doing it crude way.
Getting all the favorites and checking the size and then pushing the new object into it.

Is there any better approach using mongodb query operators ?

I want to check the size < 50 and then update array in single db call.
1

There are 1 best solutions below

0
R2D2 On

Maybe something like this:

db.collection.update({
  _id: "mongo_id",
  "favorites.50": {
   "$exists": false
}
},
{
"$push": {
favorites: {
  obj: 10
  }
}
})

Explained:

  1. Find document to update by _id where favorites[50] element do not exists

( array element 50 will not exists for all documents with < 50 favorites )

  1. $push the new object in the document

Playground