【问题标题】:MongoDB compound sparse indexesMongoDB 复合稀疏索引
【发布时间】:2018-01-22 08:14:31
【问题描述】:

我有一个followig复合索引:

db.nodes.createIndex( { parent: 1, name: 1 }, { unique: true } );

该索引禁止插入两个具有相同名称和父级的文档 例如:

var n=db.nodes;
n.insert({parent:0,name:"node"});
n.insert({parent:0,name:"node1"});
n.insert({parent:0,name:"node2"});
n.insert({parent:0,name:"node3"});
//throws an error because of compound index:
n.insert({parent:0,name:"node"});

没关系。现在,如果名称为空(或不存在),我想添加多个具有相同父级的文档(例如通过稀疏单个索引)。有可能吗? 示例:

n.insert({parent:0,otherattr:"test"});
//throws an error because the tupel {parent:0,name:null} already exists
 n.insert({parent:0,otherattr2:"test"});

【问题讨论】:

    标签: mongodb compound-index


    【解决方案1】:

    您可以通过为您的唯一索引定义 partial filter expression 来做到这一点:

    db.nodes.createIndex(
        { parent: 1, name: 1 }, 
        { unique: true,
          partialFilterExpression: {
            name: {$exists: true}
          } 
        });
    

    过滤器表达式从唯一索引中排除没有name 的文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 2017-02-13
      • 1970-01-01
      • 2018-06-12
      • 2012-07-07
      • 1970-01-01
      相关资源
      最近更新 更多