MongoDB find by max value in array of documents
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"} } }
])