Reputation: 824
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
Reputation: 10737
Maybe something like this:
db.collection.update({
_id: "mongo_id",
"favorites.50": {
"$exists": false
}
},
{
"$push": {
favorites: {
obj: 10
}
}
})
Explained:
( array element 50 will not exists for all documents with < 50 favorites )
Upvotes: 0