簡體   English   中英

僅當mongo集合中子數組的大小小於50時,如何將新項目添加到特定文檔的子數組

[英]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
  }
}
})

解釋:

  1. 通過 _id 查找要更新的文檔,其中 favorites[50] 元素不存在

(收藏夾 < 50 的所有文檔都不會存在數組元素 50 )

  1. $push 文檔中新的 object

操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM