Tuesday 30 May 2017

Find max value for element in array with MongoDB

I have a collection of sensor data where each document has the following structure:

[{ _id: 592d9b0e276bd2136caacca0,
    name: 5
    light: [ ... ],
    temperature: [ ... ],
    UV: [ ... ],
    RA: [ ... ]
}]

Each array of each sensor has a length of 100 elements.

How can I, for example, retrieve which name has the document with the highest value for the temperature at position 42 (in the array of temperature )?

There are a lot of solutions for the first element or last element but I can't seem to find how to solve it for arbitrary positions of the array.

This is what I already have:

db.sensors.aggregate([
    { $unwind: "$name" },
    { $sort: { "temperature": -1} },
    { $limit: 1}
]);

But as you see, the line with "{ $sort: { "temperature": -1 } }" will not work. I really do not understand how to specify that I want the sorting only for the element at position 42 of the temperature array.



via dll

No comments:

Post a Comment