In Mongodb , how do I check if all the documents are unique for a value?

前端 未结 1 1573
故里飘歌
故里飘歌 2021-01-19 10:17

Let\'s say I have 4 documents in the database:

{ name: \'alex\' }
{ name: \'jen\' }
{ name: \'alex\' }
{ name: \'john\'}

In MongoDB Shell,

1条回答
  •  悲&欢浪女
    2021-01-19 11:04

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

    0 讨论(0)
提交回复
热议问题