MongoDB按文档数组中的最大值查找 [英] MongoDB find by max value in array of documents
问题描述
提供包含以下文件的集合:
Given a collection with documents such as:
{
"host" : "example.com",
"ips" : [
{
"ip" : NumberLong("1111111111"),
"timestamp" : NumberLong(1373970044)
},
{
"ip" : NumberLong("2222222222"),
"timestamp" : NumberLong(1234978746)
}
]
}
我需要返回所有ip值为X的文档,但前提是X的关联时间戳是ips数组中最高时间戳(因此,上述示例文档不应 匹配搜索"2222222222",因为这不是不是具有最新时间戳的IP.
I need to return all documents with an ip value of X, but only if the associated timestamp for X is the highest timestamp in the ips array (so the above example document should not match a search for "2222222222" because that is not the IP with the most recent timestamp).
这是我第一次在MongoDB中做一些超出基本内容的事情,所以我能得到的最接近的是:
This is my first time doing anything much beyond fairly basic stuff in MongoDB so the closest I've been able to get is:
coll.aggregate({$ match:{"ips.ip":X}},{$ group:{"_ id":"$ host", "max":{$ max:"$ ips.timestamp"}}},{$ sort:{"ips.timestamp":-1}}).
coll.aggregate({$match:{"ips.ip":X}},{$group:{"_id":"$host", "max":{$max:"$ips.timestamp"}}},{$sort:{"ips.timestamp":-1}}).result
这显然不能满足我的要求,它会返回ips.ip值为X的任何内容.仅当X的关联时间戳最高时,我才能仅返回ip.ip为X的文档. ips数组?
Which obviously doesn't give me what I'm looking for, it returns anything with an ips.ip value of X. How do I return only documents where ip.ip is X only if X's associated timestamp is the highest for that ips array?
推荐答案
如果host
是唯一的,则以下代码可以完成此工作.否则,您可以在分组操作中将host
替换为_id
:
If host
is unique, the following code should do the job. Otherwise, you can simply replace host
by _id
in the grouping operation:
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"} } }
])
这篇关于MongoDB按文档数组中的最大值查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!