"_id"로 정의 된 문서에서 하위 문서의 배열에서 최신 항목을 가져와야합니다.
문서는 다음과 같습니다
이 쿼리와{
"_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
}
]
}
]}
내가 "도구 1"의 전체 역사를 얻을 :
db.users.find(
{
"_id": "nex67",
"ownedparts.id": "tool1"
}, { "ownedparts.history.$": 1 })
그리고 난 최신 항목을받을 수 있나요 명령으로
하지만 반환 "tool1"과 "screw1"둘 다에서 :db.users.find(
{"_id": "nex67"},
{"ownedparts.history": { $slice: -1 }})
그래서 기본적으로 나는이 쿼리를 결합하는 데 도움이 필요합니다. nex67의 tool1에서 최신 기록 항목을 가져올 수 있습니다.
내가 다음과 같아야 필요 결과 :
{
"_id" : "nex67",
"ownedparts" : [
{
"id" : "tool1",
"history" : [
{
"time" : ISODate("2016-06-07T09:12:54.015Z"),
"value" : 240
}
]
}
]}
'$ arrayElemAt' 안에'$ filter'의 완벽한 조합! – profesor79