[英]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
我的 mongoDB 中有一個用戶集合。現在我只想更新收藏夾數組,前提是它的大小小於 50。
"_id": 'mongo_id',
"name": "test user",
"email": "test_4@gmail.com",
"full_name": "",
"first_name": "",
"last_name": "",
"mobile_number": "",
"email_id": "test_4@gmail.com",
"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.
也許是這樣的:
db.collection.update({
_id: "mongo_id",
"favorites.50": {
"$exists": false
}
},
{
"$push": {
favorites: {
obj: 10
}
}
})
解釋:
(收藏夾 < 50 的所有文檔都不會存在數組元素 50 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.