按子文档字段分组文档

问题描述 投票:1回答:2

我正在尝试使用mongo的聚合框架根据时间戳对集合进行分组,并使用$ out将其输出到新集合。道歉,我是Mongo的新手

我的集合中有以下JSON结构

{
    "_id" : "1",
    "parent" : [
        {
            "child" : {
                "child_id" : "1",
                "timestamp" : ISODate("2010-01-08T17:49:39.814Z")
            }
        }
    ]
}

这是我一直在尝试的

db.mycollection.aggregate([
        { $project: { child_id: '$parent.child.child_id', timestamp: '$parent.child.timestamp' }},
        { $group: { cid: '$child_id', ts: { $max: '$timestmap'} }},
        { $out : 'mycollectiongrouped'}
        ]))

但是得到这个错误。任何想法,我认为我可能错误地使用该项目。

[thread1]错误:命令失败:{“ok”:0,“errmsg”:“组聚合字段'cid'必须定义为对象内的表达式”,“代码”:15951}:聚合失败:_getErrorWithCode @ SRC /蒙戈/壳/ utils.js:25:13

mongodb mongodb-query aggregation-framework
2个回答
1
投票
db.collection.aggregate([
    {$group: { 
        _id: "$parent.child.child_id",
        timestamp: {$max: "$parent.child.timestamp"}
    }},
    {$project: {
        cid: {$arrayElemAt: ["$_id", 0]},
        ts: {$arrayElemAt: ["$timestamp", 0]},
        _id: 0
    }},
    {$out: "groupedCollection" }
])

你错过了_id管道阶段必需的$group。这就是说,因为文档中的“父”字段是一个元素数组,所以$group阶段应该是管道中的第一个阶段。

通过将$group阶段作为第一阶段,您只需要为每个组生成一个文档而不是集合中的所有文档。

请注意,生成的文档字段是数组,因此在$arrayElemAt阶段使用$project运算符。


0
投票

你需要一个_id字段为$group。这个_id决定了哪些文档组合在一起。例如,如果你想通过child_id分组,那么就做_id: "$child_id"。在这种情况下,您可以省略cid字段(在这种情况下,您只需将cid更改为_id)。

© www.soinside.com 2019 - 2024. All rights reserved.