I need to get the latest entry from subdocument's array from a document defined by "_id".
The document looks like this:
{
"_id": "nex67",
"ownedparts": [
{
"id": "tool1",
"history": [
{
"time": ISODate("2016-06-07T09:12:54.015Z"),
"value": 300
},
{
"time": ISODate("2016-06-07T09:12:54.015Z"),
"value": 240
}
]
},
{
"id": "screw1",
"history": [
{
"time": ISODate("2016-06-07T09:12:54.015Z"),
"value": 500
}
]
}
]}
With this query i get full history of "tool1":
db.users.find(
{
"_id": "nex67",
"ownedparts.id": "tool1"
}, { "ownedparts.history.$": 1 })
And with this command i do get the latest entry, but it returns them from both "tool1" and "screw1":
db.users.find(
{"_id": "nex67"},
{"ownedparts.history": { $slice: -1 }})
So basically i need help combining these queries so that i can get the latest history entry from nex67's tool1.
The result i need should look like this:
{
"_id" : "nex67",
"ownedparts" : [
{
"id" : "tool1",
"history" : [
{
"time" : ISODate("2016-06-07T09:12:54.015Z"),
"value" : 240
}
]
}
]}