2017-08-14 71 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