MongoDB在文档数组中按最大值查找

时间:2013-07-18 21:04:07

标签: mongodb

给出一个包含以下文档的集合:

{
    "host" : "example.com",
    "ips" : [
        {
            "ip" : NumberLong("1111111111"),
            "timestamp" : NumberLong(1373970044)
        },
        {
            "ip" : NumberLong("2222222222"),
            "timestamp" : NumberLong(1234978746)
        }
    ]
}

我需要返回ip值为X的所有文档,但前提是X的关联时间戳是ips数组中的最高时间戳(因此上面的示例文档应匹配搜索“2222222222”,因为具有最新时间戳的IP。)

这是我第一次在MongoDB中做一些非常基本的东西,所以我能得到的最接近的是:

  

coll.aggregate({$匹配:{ “ips.ip”:X}},{$组:{ “_ ID”: “$主机”,   “最大值”:{$最大: “$ ips.timestamp”}}},{$排序:{ “ips.timestamp”: - 1}})导致

这显然没有给我我正在寻找的东西,它返回任何ips.ip值为X.如果X的关联时间戳最高,我怎么才返回ip.ip为X的文件那个ips阵列?

3 个答案:

答案 0 :(得分:12)

如果Host是唯一的,则以下代码应该完成此任务。否则,您只需在分组操作中通过_id替换主机

coll.aggregate([
  {$unwind: "$ips"},
  {$project:{host:"$host",ip:"$ips.ip", ts:"$ips.timestamp"} },
  {$sort:{ts:1} },
  {$group: {_id: "$host", IPOfMaxTS:{$last: "$ip"}, ts:{$last: "$ts"} } }
])

我希望它有所帮助。

答案 1 :(得分:1)

从mongo 3.4版本开始,您可以在聚合管道中使用$reduce

db.t64.aggregate([
    {$addFields : {ips : {$reduce : {
        input : "$ips", 
        initialValue : {timestamp : 0}, 
        in : {$cond: [{$gte : ["$$this.timestamp", "$$value.timestamp"]},"$$this", "$$value"]}}
    }}}
])

样品采集

> db.t64.findOne()
{
        "_id" : ObjectId("5c45e00f328877e101354d97"),
        "host" : "example.com",
        "ips" : [
                {
                        "ip" : NumberLong(1111111111),
                        "timestamp" : NumberLong(1373970044)
                },
                {
                        "ip" : NumberLong("2222222222"),
                        "timestamp" : NumberLong(1234978746)
                }
        ]
}

输出

> db.t64.aggregate([ {$addFields : {ips : {$reduce : { input : "$ips",  initialValue : {timestamp : 0},  in : {$cond: [{$gte : ["$$this.timestamp", "$$value.timestamp"]},"$$this", "$$value"]}} }}} ])
{ "_id" : ObjectId("5c45e00f328877e101354d97"), "host" : "example.com", "ips" : { "ip" : NumberLong(1111111111), "timestamp" : NumberLong(1373970044) } }

答案 2 :(得分:0)

IN Simple Words , 如果您有 mongo查询响应,如下所示 - 并且您只需要来自 Array->的最高值“日期”

{
  "_id": "57ee5a708e117c754915a2a2",
  "TotalWishs": 3,
  "Events": [
    "57f805c866bf62f12edb8024"
  ],
  "wish": [
    "Cosmic Eldorado  Mountain Bikes, 26-inch (Grey/White)",
    "Asics Men's Gel-Nimbus 18 Black, Snow and Fiery Red Running Shoes - 10 UK/India (45 EU) (11 US)",
    "Suunto Digital Black Dial Unisex Watch - SS018734000"
  ],
  "Date": [
    "2017-02-13T00:00:00.000Z",
    "2017-03-05T00:00:00.000Z"
  ],
  "UserDetails": [
    {
      "createdAt": "2016-09-30T12:28:32.773Z",
      "jeenesFriends": [
        "57edf8a96ad8f6ff453a384a",
        "57ee516c8e117c754915a26b",
        "58a1644b6c91d2af783770b0",
        "57ef4631b97d81824cf54795"
      ],
      "userImage": "user_profile/Male.png",
      "email": "roopak@small-screen.com",
      "fullName": "Roopak Kapoor"
    }
  ],

},

***然后你添加了

  

Latest_Wish_CreatedDate:{$ max:“$ Date”},

如下所示 -

{ 
                $project : { _id: 1,
                             TotalWishs : 1 ,
                              wish:1 ,
                               Events:1, 
                               Wish_CreatedDate:1,
                               Latest_Wish_CreatedDate: { $max: "$Date"},
                            } 
            } 

最终查询响应将低于

{
  "_id": "57ee5a708e117c754915a2a2",
  "TotalWishs": 3,
  "Events": [
    "57f805c866bf62f12edb8024"
  ],
  "wish": [
    "Cosmic Eldorado  Mountain Bikes, 26-inch (Grey/White)",
    "Asics Men's Gel-Nimbus 18 Black, Snow and Fiery Red Running Shoes - 10 UK/India (45 EU) (11 US)",
    "Suunto Digital Black Dial Unisex Watch - SS018734000"
  ],
  "Wish_CreatedDate": [
    "2017-03-05T00:00:00.000Z",
    "2017-02-13T00:00:00.000Z"
  ],
  "UserDetails": [
    {
      "createdAt": "2016-09-30T12:28:32.773Z",
      "jeenesFriends": [
        "57edf8a96ad8f6ff453a384a",
        "57ee516c8e117c754915a26b",
        "58a1644b6c91d2af783770b0",
        "57ef4631b97d81824cf54795"
      ],
      "userImage": "user_profile/Male.png",
      "email": "roopak@small-screen.com",
      "fullName": "Roopak Kapoor"
    }
  ],
  "Latest_Wish_CreatedDate": "2017-03-05T00:00:00.000Z"
},