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

Exu*_*ery 7 mongodb

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

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

我需要与X的IP值返回所有文件,但只有当X相关的时间戳是最高的IPS阵列中的时间戳(所以上面的例子中文件应该匹配"2222222222"的搜索,因为这是没有的IP最近的时间戳).

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

coll.aggregate({$ match:{"ips.ip":X}},{$ group:{"_ id":"$ host","max":{$ max:"$ ips.timestamp"}}} {$排序:{ "ips.timestamp": - 1}})导致

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

inn*_*SPG 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"} } }
])
Run Code Online (Sandbox Code Playgroud)

我希望它有所帮助.

  • 谢谢,这个$ unwind函数对我来说也有类似的问题. (2认同)