I have a collection with documents with next structure:
{
"Id" : 123
"History" : [
{
"MachineId" : 1,
"Time" : ISODate("2014-02-10T13:10:00Z"),
"Status" : 0
},
{
"MachineId" : 1,
"Time" : ISODate("2014-02-10T13:10:44Z"),
"Status" : 1
},
{
"MachineId" : 2,
"Time" : ISODate("2014-02-10T13:10:50Z"),
"Status" : 2
}
]
},
{
"Id" : 345
"History" : [
{
"MachineId" : 1,
"Time" : ISODate("2014-02-10T13:10:00Z"),
"Status" : 0
},
{
"MachineId" : 1,
"Time" : ISODate("2014-02-10T13:10:44Z"),
"Status" : 1
}
]
}
I have an input MachineId and Status and I want to find all documents that have the nested History item with given MachineId and Status, but this item must be the most recent one.
For example, for MachineId=1 and Status=1, I want get only the document with Id=345
I know how to query nested array elements, but here I need first to sort the history array to find the last added item. I have no idea how to do this in MongoDB.