我有一个集合:“foo”
foo: {name: 'steve'}
因此,要使名称成为唯一索引,您可以运行:
db.foo.ensureIndex( {{name: 1}}, { unique: true } )
但是我想做的是确保只允许一个值为“steve”的名称。有没有办法使一个字段成为唯一索引,但指定它只应在该属性的值具有特定值时执行?
伪查询..... db.foo.ensureIndex( {{name: 'steve'}}, { unique: true } )
好
foo: {name: 'steve');
foo: {name: 'chris'};
foo: {name: 'chris'};
foo: {name: 'mike'};
foo: {name: 'mike'};
不好
foo: {name: 'steve');
foo: {name: 'steve'};
foo: {name: 'chris'};
foo: {name: 'chris'};
foo: {name: 'mike'};
foo: {name: 'mike'};
最佳答案
如果你真的,真的绝望,让你的值(value)成为关键:
db.uniq.insert( { "name" : {"steve" : null } });
db.uniq.insert( { "name" : {"john" : null } });
db.uniq.ensureIndex( {"name.steve" : 1}, {unique : true, sparse: true} );
代替 null
,您可以使用 1
或 "bogus"
或其他任何内容。只需确保它始终相同,并且最好小。
请注意,键必须是唯一的和稀疏的,否则缺少的steve
字段将被解释为"steve":空
。因为稀疏键实际上只在单个文档上,所以我猜这个解决方案甚至不是特别昂贵。
关于mongodb - Mongo,强制集合中的特定字段具有唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19433944/