2017-08-14 66 views
1

我有一个followig化合物索引:MongoDB的化合物稀疏索引

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

该索引forbides至插入两个文档具有相同名称和父 例如:

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"}); 

回答

2

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

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

过滤表达式不包括文档,而无需name从唯一索引。

+0

它的工作原理非常感谢 – neoexpert