MongoDB compound sparse indexes

拥有回忆 提交于 2019-12-11 06:19:29

问题


I have a followig compound index:

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

that index forbides to insert two docs with same name and parent for example:

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

that is ok. Now if name is null (or not present) i want to add multiple docs with same parent (like by sparse single indexes). Is it posible? Example:

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

回答1:


You can do this by defining a partial filter expression for your unique index:

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

The filter expression excludes documents without name from the unique index.



来源:https://stackoverflow.com/questions/45675385/mongodb-compound-sparse-indexes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!