【问题标题】:Aggregate nested documents with missing data聚合缺少数据的嵌套文档
【发布时间】:2020-08-22 19:34:09
【问题描述】:

我有一个 mongoDB 集合,其中包含以下数据:

{
    "_id" : ObjectId("..."),
    "records" : [
        ISODate("2020-04-19T00:49:18.945Z"),
        {
            "_id" : ObjectId(""),
            "date" : ISODate("2020-05-07T04:49:55.643Z"),
            "text" : "someText"
        }
    ],
}

records中的值因版本升级而不同。

我想在所有文档中聚合records.text,忽略丢失的数据。来自MongoDB: Aggregate and flatten an array field的代码

db.collection.aggregate({$unwind : "records"},
                      {$project: {_id: 1, 'text': '$records.text'}})

抛出:

path option to $unwind stage should be prefixed with a '$': records

并修复来自 these directions 的错误以适应空字段:

db.collection.aggregate({$unwind : "records", includeEmpty: false},
                      {$project: {_id: 1, 'text': '$records.text'}})

抛出

A pipeline stage specification object must contain exactly one field.

如何从可能为空值的嵌套数组中聚合值?

【问题讨论】:

    标签: javascript mongodb aggregation-framework


    【解决方案1】:

    您可以使用$exists 过滤掉空的:

    db.collection.aggregate([
        { $unwind: "$records" },
        { $match: { "records.text": { $exists: true } } },
        { $project: { _id: 1, text: "$records.text" }}
        {$group: {_id: "$text", count: {$sum: 1}}},
        {$sort: {count: -1}}
    ])
    

    Mongo Playground

    【讨论】:

      【解决方案2】:

      在您的第一个查询中,您缺少“$”,因为记录是一个字段值,因此您应该在它前面加上“$”。最终查询将是:

      db.collection.aggregate({$unwind : "$records"},
                            {$project: {_id: 1, 'text': '$records.text'}})
      

      我希望这对你有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-14
        • 2020-07-26
        • 1970-01-01
        • 2021-06-04
        • 1970-01-01
        • 1970-01-01
        • 2020-11-13
        • 1970-01-01
        相关资源
        最近更新 更多