通过数组元素比较查找

时间:2017-01-24 19:48:15

标签: mongodb mongodb-query aggregation-framework

我们说我有一个名为test的集合:

> db.test.find()
{ "_id" : ObjectId("5887a9202d599801b7df2c3c"), "name" : "soccer66", "ratings" : [ 5, 3.2, 1 ] }
{ "_id" : ObjectId("5887a9232d599801b7df2c3d"), "name" : "user1", "ratings" : [ 2, 3.2, 1 ] }
{ "_id" : ObjectId("5887a9262d599801b7df2c3e"), "name" : "user2", "ratings" : [ 2.5, 4.9, 1 ] }

选择第一个评级大于第二个评分的文档的最佳方法是什么?我尝试过很多疑问。为了这篇文章,我再次运行了以下内容:

> db.test.aggregate([
         {$project:{"isGreater":{$cond:[{$gt:["$ratings.0","$ratings.1"]},true,false]}}},
         {$match:{"isGreater": true}}]);
>

> db.test.find({$where: "this.ratings.0" < "this.ratings.1"});
Error: error: {
  "ok" : 0,
  "errmsg" : "$where got bad type",
  "code" : 2,
  "codeName" : "BadValue"
}
     

db.test.find({&#34; ratings.0&#34;:{&#34; $ gt&#34;:&#34; ratings.1&#34;}});

证明我使用正确的数组索引和评级。#:

> db.test.find({"ratings.0":5});
{ "_id" : ObjectId("5887a9202d599801b7df2c3c"), "name" : "soccer66", "ratings" : [ 5, 3.2, 1 ] }
>

2 个答案:

答案 0 :(得分:3)

在你的$where语句整数中“谓词应该在引号中:

db.test.find({$where: "this.ratings[0] < this.ratings[1]"});

答案 1 :(得分:2)

Do not use the $where operator.

您应该使用聚合框架。

db.test.aggregate([
    { "$match": { "ratings.1": { "$exists": true } } },
    { "$redact": {
        "$cond": [
            { "$gt": [
                { "$arrayElemAt": [ "$ratings", 0 ] },
                { "$arrayElemAt": [ "$ratings", 1 ] }
            ]},
            "$$KEEP",
            "$$PRUNE"
        ]
    }}
])