Reputation: 185
I have a collection of documents like these:
{
"_id": numeric-id,
"timestamp": a-timestamp,
"odd1": "3.45",
"odd2": "1.95",
"odd3": "4.05",
"source": "a"
}
I managed to aggregate the records using this snippet:
{
$group: {
_id: {tm: "$timestamp"},
odd1: {$max: "$odd1"},
odd2: {$max: "$odd2"},
odd3: {$max: "$odd3"}
}
}
In addition to the maximum odd of each cathegory, I also need the corresponding field 'source' that provides the maximum odd. Is there a way for asking this to mongo?
Upvotes: 2
Views: 66
Reputation: 5529
You can't do that in MongoDB, but you can do a second query, to find out out the source of each maxx odd, at all timestamps:
var agg = db.collection.aggregate(
{
$group: {
_id: {tm: "$timestamp"},
odd1: {$max: "$odd1"},
odd2: {$max: "$odd2"},
odd3: {$max: "$odd3"}
}
}
);
while (agg.hasNext()) {
var o = agg.next();
var timestamp_odd1 = db.collection.findOne({timestamp: o['_id']['tm'],odd1:o['odd1']});
var timestamp_odd2 = db.collection.findOne({timestamp: o['_id']['tm'],odd2:o['odd2']});
var timestamp_odd3 = db.collection.findOne({timestamp: o['_id']['tm'],odd3:o['odd3']});
print ("timestamp: ", o._id.tm,' max_odd1:', timestamp_odd1['odd1'], ' ', 'source: ', timestamp_odd1['source']) ;
print ("timestamp: ", o._id.tm,' max_odd2:', timestamp_odd2['odd2'], ' ', 'source: ', timestamp_odd2['source']) ;
print ("timestamp: ", o._id.tm,' max_odd3:', timestamp_odd3['odd3'], ' ', 'source: ', timestamp_odd3['source']) ;
}
Upvotes: 1