我需要从“_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
}
]
}
]}
通过此查询,我可以获得“tool1”的完整历史记录:
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
}
]
}
]}
最佳答案
执行此操作的最佳方法是在 MongoDB 3.2 中使用 $arrayElemAt
和 $filter
运算符。
db.users.aggregate(
[
{ "$match": { "_id": "nex67", "ownedparts.id": "tool1" } },
{ "$project": {
"ownedparts": {
"$let": {
"vars": {
"el": {
"$arrayElemAt": [
{ "$filter": {
"input": "$ownedparts",
"as": "own",
"cond": { "$eq": [ "$$own.id", "tool1" ] }
}},
0
]
}
},
"in": {
"id": "$$el.id",
"history": { "$arrayElemAt": [ "$$el.history", -1 ] }
}
}
}
}}
]
)
产生:
{
"_id" : "nex67",
"ownedparts" : {
"id" : "tool1",
"history" : {
"time" : ISODate("2016-06-07T09:12:54.015Z"),
"value" : 240
}
}
}
关于mongodb - 从子文档数组中查找数据时使用 $slice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37688307/