Get documents with tags in list, ordered by total number of matches

后端 未结 3 1460
梦谈多话
梦谈多话 2020-12-09 06:36

Given the following MongoDB collection of documents :

{
 title : \'shirt one\'
 tags : [
  \'shirt\',
  \'cotton\',
  \'t-shirt\',
  \'black\'
 ]
},
{
 title         


        
3条回答
  •  失恋的感觉
    2020-12-09 07:08

    I'll second @Bryan in saying that MapReduce is the only possible way at the moment (and it's far from perfect). But, in case you desperately need it, here you go :-)

        var m = function() {
            var searchTerms = ['shirt', 'cotton', 'black'];
            var me = this;
            this.tags.forEach(function(t) {
                searchTerms.forEach(function(st) {
                    if(t == st) {
                        emit(me._id, {matches : 1});
                    }
                })
            })
        };
    
        var r = function(k, vals) {
            var result = {matches : 0};
            vals.forEach(function(v) {
                result.matches += v.matches;
            })
            return result;
        };
    
        db.shirts.mapReduce(m, r, {out: 'found01'});
    
        db.found01.find();
    

提交回复
热议问题