mongoDB有没有办法让聚合$ gte不显示错误数据

时间:2016-09-06 09:04:42

标签: mongodb mongodb-query aggregation-framework

https://docs.mongodb.com/manual/reference/operator/aggregation/gte/

正如您在上面的mongo db文档中看到的那样,$ gte也会返回错误的数据。

示例json数据:

{ "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 }
{ "_id" : 2, "item" : "abc2", description: "product 2", qty: 200 }
{ "_id" : 3, "item" : "xyz1", description: "product 3", qty: 250 }
{ "_id" : 4, "item" : "VWZ1", description: "product 4", qty: 300 }
{ "_id" : 5, "item" : "VWZ2", description: "product 5", qty: 180 }

查询获取数据大于250的数据:

db.inventory.aggregate(
   [
     {
       $project:
          {
            item: 1,
            qty: 1,
            qtyGte250: { $gte: [ "$qty", 250 ] },
            _id: 0
          }
     }
   ]
)

输出:

{ "item" : "abc1", "qty" : 300, "qtyGte250" : true }
{ "item" : "abc2", "qty" : 200, "qtyGte250" : false }
{ "item" : "xyz1", "qty" : 250, "qtyGte250" : true }
{ "item" : "VWZ1", "qty" : 300, "qtyGte250" : true }
{ "item" : "VWZ2", "qty" : 180, "qtyGte250" : false }

问题: 好吧,我想要数据,其中qty> 250,但mongo db显示所有数据,因此当记录数量如此之高时,网站变得如此慢。

我在带有mongoid的rails上使用ruby,我有一些查询,我需要使用group by子句,所以我必须聚合,但这是返回所有数据。 我原来的查询:

data = SomeModel.collection.aggregate([
      {"$project" => {
        "dayOfMonth" => {"$dayOfMonth" => "$created_time"},
        "month" => {"$month" => "$created_time"},
        "year" => {"$year" => "$created_time"},
        "date_check_gte" => {"$gte" => ["$created_time",start_time]},
        "date_check_lte" => {"$lte" => ["$created_time",end_time]},
      }},
      {"$group" => {
        "_id" => { "dayOfMonth" => "$dayOfMonth", "month" => "$month", "year" => "$year"},
        "Total" => {"$sum" => 1},
        "check_one" => {"$first" => "$date_check_gte"},
        "check_two" => {"$first" => "$date_check_lte"}
      }},
      {"$sort" => {
        "Total" => 1
      }}
    ])

完美分组,但尽管使用了gte和lte,但仍会返回所有数据。 有什么可以做的,以便不会出现虚假数据吗?

2 个答案:

答案 0 :(得分:2)

您是否尝试在管道中使用$match来过滤qty > 250的文档?

例如:

db.inventory.aggregate(
   [ {$match: {qty: {$gt: 250}}},
     {
       $project:
          {
            item: 1,
            qty: 1,
            _id: 0
          }
     }
   ]
)

答案 1 :(得分:2)

"查询"获取数据大于250的数据涉及 $match 管道运算符,该运算符过滤文档以仅将符合指定条件的文档传递到下一个管道阶段,而不是您正在进行的 $project 管道:

db.inventory.aggregate([
    { "$match": { "qty": { "$gte": 250 } } }   
)

或使用相同的 $project 管道(虽然没有必要,因为上面只使用一个 $match 管道就足够了):

db.inventory.aggregate([
    {
        "$project": {
            "item": 1,
            "qty": 1,
            "qtyGte250": { "$gte": [ "$qty", 250 ] },
            "_id": 0
        }
    },
    { "$match": { "qtyGte250": true } }   
])
相关问题