MongoDB复合稀疏索引 [英] MongoDB compound sparse indexes

查看:115
本文介绍了MongoDB复合稀疏索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Followig复合索引:

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

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

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

推荐答案

您可以通过定义局部过滤表达式,用于您的唯一索引:

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

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

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

这篇关于MongoDB复合稀疏索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆