2016-09-06 59 views
1

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

,你可以在上面蒙戈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

“查询”用于获取数据,其中数量大于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 } } 
]) 
2

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

例:

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