【问题标题】:Are _ids in a sub document array assured to be unique within that array子文档数组中的 _ids 是否保证在该数组中是唯一的
【发布时间】:2018-12-29 03:18:48
【问题描述】:

MongoDB

我知道,如果您有一个子文档数组,并且您在这些子文档上为某个字段编制索引,则该字段只能确保在整个集合中是唯一的,而不是在该单个数组中。

这同样适用于那些子文档的 _id 属性吗? 例如,如果我有以下

{
  _id: 'Parent ID',
  subdocArray: [
    {
      _id: 'Child ID 1'
    }
  ]
}

我决定将另一个子文档添加到数组中,确保 _id 字段的唯一性与在常规顶级文档中的方式相同。

【问题讨论】:

    标签: arrays mongodb subdocument unique-id


    【解决方案1】:

    不,_id 在子文档数组中对 MongoDB 没有特殊意义。

    但是,正如 here 所问的那样,您可以在向数组添加元素时手动强制执行此所需的限制。

    db.coll.update(
        {_id: 'Parent ID', 'subdocArray._id': {$ne: 'Child ID 1'}}, 
        {$push: {subdocArray: {_id: 'Child ID 1'}}})
    

    【讨论】:

      猜你喜欢
      • 2021-07-28
      • 1970-01-01
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      • 2011-02-19
      相关资源
      最近更新 更多