mongodb - 是否有一个查询可以连接深层子列表?

标签 mongodb mongodb-query aggregation-framework

在我的数据库中,我有一个文档列表,每个文档本身都包含另一个文档列表,后者是一些数据的列表,其中时间戳自纪元以来存储为毫秒。

以下是示例数据集:

{
    "_id" : ObjectId("5da5aee33e791547bb418782"),
    "list1" : [
        {
            "document" : {
                "list2" : [
                    {
                        "sub-document" : {
                            "timestamp" : 100
                        }
                    },
                    {
                        "sub-document" : {
                            "timestamp" : 105
                        }
                    },
                    {
                        "sub-document" : {
                            "timestamp" : 110
                        }
                    }
                ]
            }
        },
        {
            "document" : {
                "list2" : [
                    {
                        "sub-document" : {
                            "timestamp" : 101
                        }
                    },
                    {
                        "sub-document" : {
                            "timestamp" : 104
                        }
                    },
                    {
                        "sub-document" : {
                            "timestamp" : 109
                        }
                    }
                ]
            }
        }
    ]
}

是否可以从所有“第二层”列表中查询例如2个最新文档?

预期输出是:

[
    {
        "sub-document": {
            "timestamp": 109
        }
    },
    {
        "sub-document": {
            "timestamp": 110
        }
    }
]

最佳答案

您需要$unwind申请前两次$sort然后你可以使用$limit只得到两个元素。您还可以运行$replaceRoot子文档提升到结果的根级别:

db.collection.aggregate([
    { $unwind: "$list1" },
    { $unwind: "$list1.document.list2" },
    { $sort: { "list1.document.list2.sub-document.timestamp": -1 } },
    { $limit: 2 },
    { $replaceRoot: { newRoot: "$list1.document.list2.sub-document" } },
    { $sort: { "timestamp": 1 } }
])

Mongo Playground

关于mongodb - 是否有一个查询可以连接深层子列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58393374/

相关文章:

mongodb - 将 mongo 查询的输出重定向到 csv 文件

MongoDB:如何查找仅包含最新更改信息的文档?

mongodb - 首先按类别分组,然后按周或月分组

mongodb - "Not authorized on ___ to execute command"与 mLab + MongoDB ^3.0

mongodb - 如何获取mongodb中的最后N条记录?

MongoDB 表设计和查询性能

mongodb - 如何将嵌入式文档数组移动到父级并使用聚合管道更改键/值

angularjs - 更新$http返回数据到html View

MongoDB 聚合管道在第一个匹配步骤后变慢

mongodb - 如果输入数组的元素至少匹配一个,则获取数组的大小