首页 文章

按子文档字段分组文档

提问于
浏览
1

我正在尝试使用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

2 回答

  • 0

    $group 需要一个 _id 字段 . 这个 _id 决定了哪些文档组合在一起 . 例如,如果要按 child_id 进行分组,则执行 _id: "$child_id" . 在这种情况下,您可以省略 cid 字段(在这种情况下,您只需将 cid 更改为 _id ) .

  • 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" }
    ])
    

    您缺少$group,这对于$group管道阶段是必需的 . 这就是说,因为文档中的"parent"字段是一个元素数组, $group 阶段应该是管道中的第一个阶段 .

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

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

相关问题