Multiple $where queries in MongoDB

后端 未结 2 997
南方客
南方客 2021-01-26 00:57

I tried to put following query together, but it is not working:

db.sss.find({
    \"pos\": { \"$gte\": 200000, \"$lt\": 2000000 },
    \"$where\": \"(this.chr.le         


        
2条回答
  •  滥情空心
    2021-01-26 01:10

    I guess somewhat you mixed the syntax between JavaScript and MongoDB.
    $where executed by JavaScript engine on server side, so your $where statements must conform the syntax of JavaScipt. For example, this.chr.no == 5 is actually this.chr[index].no == 5 as you expected; and a variable is impossibly equal to two different values at the same time. The following codes for your reference:

    var judge = function () {
        var unexpect = "X";
        var letter1 = unexpect, letter2 = unexpect;
        for (var i in this.chr) {
            var chr = this.chr[i];
            if (chr.no == 5) {
                letter1 = chr.letter;
            } else if (chr.no == 6) {
                letter2 = chr.letter;
            }
        }
        if (letter1 != letter2 && letter1 != unexpect && letter2 != unexpect) {
            return true;
        }
        return false;
    };
    
    db.sss.find({
        "pos": { "$gte": 200000, "$lt": 2000000 },
        "$and" : [{"chr.no" : 5}, {"chr.no" : 6}],    // narrow range further
        "$where": judge
    }, {"x_type":1, "sub_name":1, "name":1, "pos":1, "s_type":1, _id:0});
    

提交回复
热议问题