在Mongodb中,如何检查所有文档是否是唯一的值? [英] In Mongodb , how do I check if all the documents are unique for a value?
本文介绍了在Mongodb中,如何检查所有文档是否是唯一的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我在数据库中有4个文档:
Let's say I have 4 documents in the database:
{ name: 'alex' }
{ name: 'jen' }
{ name: 'alex' }
{ name: 'john'}
b $ b
在MongoDB Shell中,我想知道两个或更多文档是否共享同一个'name'。
如果所有的名称不同,返回true。
如果2或人有相同的名称,则返回false。
Basically, if all the names are different, return true. If 2 or people have the same name, return false.
推荐答案
=http://www.mongodb.org/display/DOCS/MapReduce =nofollow> map-reduce查询来查找具有相同名称的文档数,所有不同的:
Try this, uses a quick map-reduce query to find the number of documents that have the same name, and returns false if they're all different:
function allDifferent() {
var m = function() { emit(this.name, 1); }
var r = function(key, emits) {
var n = 0; emits.forEach(function(v) { n += v; }); return n;
}
var result = db.mycol.mapReduce(m, r, { out: "namecounts" });
var allDifferent= (db.namecounts.count( { value: { $gt: 1 } } ) == 0)
db.namecounts.drop();
return allDifferent;
}
这篇关于在Mongodb中,如何检查所有文档是否是唯一的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文