kakurala
kakurala

Reputation: 824

How to add a new item to the sub array of a specific document only if the size of the sub array is less than 50 in mongo collection

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.

Upvotes: 0

Views: 46

Answers (1)

R2D2
R2D2

Reputation: 10737

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

Upvotes: 0

Related Questions