mongodb - 从子文档数组中查找数据时使用 $slice

标签 mongodb mongodb-query aggregation-framework

我需要从“_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/

相关文章:

mongodb - 如何在 mongodb 中更新或插入嵌套文档到数组中

node.js - 使用 Mongoose 按值仅查找数组数组中的项目

python - pymongo:删除重复项( map 减少?)

Java、Spring 数据。列表映射类型的映射实体字段

MongoDB 定价

java - 从主故障恢复后,Mongo Java 驱动程序是否恢复正常的写入操作?

java - MongoDB 和 Spring

javascript - 是否可以将映射集合名称的名称作为 MongoDB 映射函数中键的一部分包含在内?

arrays - 仅查询嵌套数组中的数字

mongodb - 涉及 mongodb 中数组字段和普通字段之和的聚合