Let\'s say I have 4 documents in the database:
{ name: \'alex\' }
{ name: \'jen\' }
{ name: \'alex\' }
{ name: \'john\'}
In MongoDB Shell,
Try this, uses a quick map-reduce query to find the number of documents that have the same name, and returns true 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;
}