基于元素位置在MongoDB中移除数组元素

6
实际上,我需要根据其位置从数组中删除一个元素。使用$pop,我们可以从顶部或底部删除元素(将其视为堆栈。 0号元素在顶部),如此处所述。这里
我们也可以使用$pull根据数组中元素的值删除元素,如此处所述这里
但是,我需要根据位置从数组中删除元素。那么有没有办法可以做到这一点?

1
这在多任务环境中并不是一个特别安全的操作。如果两个线程几乎同时尝试删除元素4会怎样呢?幂等或原子操作通常是您想要的所有数据库操作。 - Ian Mercer
3个回答

11

从文档中得知:

{ $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中有此错误

但是你可以先删除指定位置的元素,然后再拉取值为null的元素:

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

1
这样做会导致错误:"无法同时更新数组.4和数组" - Tobi

1
这是如何使用最新的MongoDB v4.2实现的,虽然不美观但可以工作。
     _id: ObjectId("5e4539cb6aebbeaa0a6b8fe7") 
   }, [
        { $set: 
          { notes: 
            { 
              $concatArrays: [
                { $slice: ['$notes', 4] }, 
                { $slice: ['$notes', { $add: [1, 4] }, { $size: '$notes' }]}
              ] 
            } 
          } 
        }
      ])```

0

以下是您的答案:如何从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. 我定义对象的作用域(确保它不会影响任何其他第一个找到的文档)
  2. 确定需要提取的元素:_permissions.view 数组中值为 "153579099841888257" 的 profile_id

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接