簡體   English   中英

根據元素的位置刪除mongoDB中的數組元素

[英]Removing the array element in mongoDB based on the position of element

實際上我需要根據它的位置從數組中刪除一個元素。 使用$流行,我們可以從頂部或底部移除元素(將其視為一個堆棧。在頂部0個元素)作為解釋在這里

我們也可以從陣列基於使用$拉作為解釋數組中的元素的值刪除元素 在這里

但是我需要根據位置從數組中刪除元素。 那么有什么辦法可以做到這一點。

從文檔:

{ $pull : { field : {$gt: 3} } } removes array elements greater than 3

所以我想你現在可以做這樣的事情:

{ $pull : { field : {$gt: 3, $lt: 5} } } // shoud remove elemet in 4 position 

或者嘗試使用位置運算符更新,我想應該是這樣的:

  { $pull : "field.4" } 

  { $pull : {"field.$": 4}}

這只是一個建議,因為我現在無法測試它。

更新:

似乎你不能一步就知道( jira中有這樣的錯誤

但是您可以使用 unset element in position 刪除並使用空值拉動元素:

{$unset : {"array.4" : 1 }}
{$pull : {"array" : null}}

這是如何使用最新的 mongodb v4.2 做到這一點的,丑陋但有效

     _id: ObjectId("5e4539cb6aebbeaa0a6b8fe7") 
   }, [
        { $set: 
          { notes: 
            { 
              $concatArrays: [
                { $slice: ['$notes', 4] }, 
                { $slice: ['$notes', { $add: [1, 4] }, { $size: '$notes' }]}
              ] 
            } 
          } 
        }
      ])```

這是您的答案: MongoDB 從集合中提取數組元素

要首先從某個文檔的數組中刪除特定元素,您需要識別此元素。 例如,我有一個帶有數組的文檔,該數組的每個元素都是一個對象:

{
    "_id" : ObjectId("5140f34888dd50971900002d"),
    "_permissions" : {
        "edit" : [
            {
                "profile_id" : NumberLong(123),
                "comment" : "app/project owner"
            },
            {
                "profile_id" : NumberLong("153579099841888257"),
                "comment" : "project admin"
            },
            {
                "profile_id" : NumberLong("153579095869882369"),
                "comment" : "project admin"
            }
        ],
        "view" : [
            {
                "profile_id" : NumberLong(123),
                "comment" : "app/project owner"
            },
            {
                "profile_id" : NumberLong("153579099841888257"),
                "comment" : "project admin"
            },
            {
                "profile_id" : NumberLong("153579095869882369"),
                "comment" : "project admin"
            }
        ]
    }
}

因此,讓我們從_permissions.view數組中刪除值為“153579099841888257”的profile_id 我們走

db.collection.update({_id: ObjectId("5140f34888dd50971900002d")}, {$pull:{"_permissions.view": {"profile_id": NumberLong("153579099841888257")}}});
  1. 我定義了對象的范圍(以確保 id 不會影響任何其他第一個找到的文檔)
  2. 確定所需元件拉出: profile_id與在“153579099841888257”值_permissions.view陣列

暫無
暫無

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

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