【问题标题】:How to delete an array element that has an index in mongoDB?如何删除在mongoDB中有索引的数组元素?
【发布时间】:2013-12-29 21:29:57
【问题描述】:

文档长这样,

{
"_id":"ffffff999999999f9ff9f9f9f",
 "Name" : "John Doe",
  "Array" : [{
      "Id1" : "a8ed3d86b8464e0cae4672cef3862860",
      "Id2" : "6d7aac14b1e142abafde167d928e3dbc",
      "Id3" : "2323232"
    }]
}

3 个数组元素的组合有一个唯一性索引。 所以索引看起来像这样,

        "key" : {
                "Array.Id1" : 1,
                "Array.Id2" : 1,
                "Array.Id3" : 1
        },
        "unique" : true,

我的要求:我想根据“_id”值查找文档并完全删除数组元素。

问题: 我正在尝试这样的事情,

db.Collection.update({"_id":"ffffffff52a8a15ce4b05d6a8d40f973"},{$unset:{Array:1}})

当我尝试取消设置数组元素时,第一次更新通过但连续更新失败并出现以下错误,

*E11000 重复键错误索引:int.Collection.$Array.Id1_1_Array.Id2_1_Array.Id3_1 重复键:{:null,:null,:null}*

我想知道这个问题是否有任何解决方法。

我必须在一个庞大的集合上运行它,并且修改索引不是一种选择。

任何建议都会很有帮助。

谢谢。

【问题讨论】:

  • 您需要修改或删除索引。

标签: mongodb


【解决方案1】:

唯一索引就是这样工作的。即使是空值(或未定义),索引字段也不能有重复项。 但是,sparse 选项允许您实现这一目标。

用法:db.collection.ensureIndex( { a: 1 }, { unique: true, sparse: true } )

因此,如果您要使用 unset 数组,您可能需要使用 sparse 选项重新索引。

Warning: Using these indexes will sometimes result in incomplete results 
when filtering or sorting results, because sparse indexes are not complete 
for all documents in a collection.

【讨论】:

  • 感谢您的帮助。因为重新索引不是我的选择。我会在更新期间尝试将值设置为其他值(一些虚拟的唯一值)。
【解决方案2】:

正如这个最小示例中所展示的,不可能从一开始就多次取消设置唯一索引字段 - 该问题不仅会在您稍后尝试取消设置时出现。

> db.coll.ensureIndex({indexField:1}, {unique: true})
> db.coll.insert({name: "doc without index field 1"})
> db.coll.insert({name: "doc without index field 2"})
E11000 duplicate key error index: test.coll.$indexField_1  dup key: { : null }

您必须用其他东西替换该字段 - 不一定是数组,但它必须是唯一的......

【讨论】:

  • 您可以使用 sparse 如另一个答案所示来允许未设置的值。
  • 谢谢。我会试试这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-20
  • 2013-06-02
  • 2016-02-25
相关资源
最近更新 更多