0

我有一个包含以下文档的 mongo 集合:

{
    "_id" : ObjectId("57697321c22d3917acd66513"),
    "parent" : "AlphaNumericID",
    "signature" : "AnotherAlphaNumericID",
    "price" : 1638,
    "url" : "http://www.thecompany.com/path/to/page1",
    "date" : ISODate("2016-06-21T17:02:20.352Z"),
    "valid" : true
}

我想要做的是运行一个查询,该查询将在签名文件上分组,返回最小和最大价格以及相应的 url:

{
        "signature" : "AnotherAlphaNumericID",  
        "min_price" : 1504,
        "min_rent_listing" : "http://www.thecompany.com/path/to/page1",
        "max_price" : 1737,
        "max_price_listing" : "http://www.thecompany.com/path/to/page2",
}

运行一个$groupon$signature字段来获取$min并且$max是直截了当的,但是为了获得实际的 url,我将查询分成 2 个,第一个查询返回一个排序的文档列表,使用$signature从 min 到 max 的价格,然后(在 python 代码中)取第一个和最后一个元素。这工作正常,但有一个查询会很好。

想法?

ps

还“玩弄”了一个查询最小值和一个最大值并“压缩”结果。

4

1 回答 1

2

$group您可以在和的帮助下耍花招$project。假设数据集是

{ 
    "_id" : ObjectId("57db28dc705af235a826873a"), 
    "parent" : "AlphaNumericID", 
    "signature" : "AnotherAlphaNumericID", 
    "price" : 1638.0, 
    "url" : "http://www.thecompany.com/path/to/page1", 
    "date" : ISODate("2016-06-21T17:02:20.352+0000"), 
    "valid" : true
}
{ 
    "_id" : ObjectId("57db28dc705af235a826873b"), 
    "parent" : "AlphaNumericID", 
    "signature" : "AnotherAlphaNumericID", 
    "price" : 168.0, 
    "url" : "http://www.thecompany.com/path/to/page2", 
    "date" : ISODate("2016-06-21T17:02:20.352+0000"), 
    "valid" : true
}
{ 
    "_id" : ObjectId("57db28dc705af235a826873c"), 
    "parent" : "AlphaNumericID", 
    "signature" : "AnotherAlphaNumericID", 
    "price" : 163.0, 
    "url" : "http://www.thecompany.com/path/to/page3", 
    "date" : ISODate("2016-06-21T17:02:20.352+0000"), 
    "valid" : true
}
{ 
    "_id" : ObjectId("57db28dc705af235a826873d"), 
    "parent" : "AlphaNumericID", 
    "signature" : "AnotherAlphaNumericID", 
    "price" : 1680.0, 
    "url" : "http://www.thecompany.com/path/to/page4", 
    "date" : ISODate("2016-06-21T17:02:20.352+0000"), 
    "valid" : true
}

在 shell 中尝试以下查询

db.collection.aggregate([
   {$sort:{price:1}},
   {$group:{
       _id:"$signature", 
       _first:{$first:"$url"},
       _last:{$last:"$url"}, 
       _min:{$first:"$price"}, 
       _max:{$last:"$price"}}
   },
   {$project:{
     _id:0, 
     min:{
       url:"$_first", 
       price:"$_min"}, 
     max:{
       url:"$_last", 
       price:"$_max"}}
   }
])

输出将带有最低/最高价格和相应的 url

{ 
    "min" : {
        "url" : "http://www.thecompany.com/path/to/page3", 
        "price" : 163.0
    }, 
    "max" : {
        "url" : "http://www.thecompany.com/path/to/page4", 
        "price" : 1680.0
    }
}

我从原来的答案改变了什么: _min:{$min:"$price"},--> 使用$first _max:{$max:"$price"}}--> 使用$last

原因:我们以价格升序进入管道。默认情况下,第一条记录是最小的,最后一条记录是最大的。

于 2016-09-15T23:44:05.800 回答