【问题标题】:Mongo Facet Aggregation with SumMongodb Facet 聚合与 Sum
【发布时间】:2020-04-30 19:09:21
【问题描述】:

试图在这个聚合中找出一些简单的东西。元数据下的“totalArrests”字段返回 0。由于某种原因,它无法对上一阶段的该字段求和。请指教。

const agg = await KID.aggregate([
        { 
            $group: {
                _id: "$source", // group by this
                title: { "$last": "$title"},
                comments: { "$last": "$comments"},
                body: { "$last": "$body"},
                date: { "$last": "$date"},
                media: { "$last": "$media"},
                source: { "$last": "$source"},
                count: { "$sum": 1},
                arrestCount: { "$sum": "$arrested"},
                rescuedCount: { "$sum": "$rescued"},
            }
        },
        // sorting
        {
            $sort: {date: sort}
        },
        // facets for paging
        {
            $facet: {
                metadata: [ 
                    { $count: "total" },  // Returns a count of the number of documents at this stage
                    { $addFields: { 
                        page: page, 
                        limit: 30,
                        totalArrests: {$sum: "$arrestCount"}
                    }},
                ],
                kids: [ { $skip: (page-1)*30 }, { $limit: 30 } ]
            }
        },
    ]);

这是集合中的示例文档。

[
  {
    _id: 5e8b922aaf5ccf5ac588398c,
    counter: 4,
    date: 2017-01-01T17:00:00.000Z,
    name: 'Steven Tucker',
    arrested: 1,
    rescued: 0,
    country: 'US',
    state: 'NH',
    comments: 'Sex trafficking of a minor',
    source: 'https://www.justice.gov/opa/pr/new-hampshire-man-indicted-sex-trafficking-minor-connection-interstate-prostitution',
    title: 'New ....',
    body: 'Steven Tucker, 31, ....',
    __v: 0,
    media: {
      title: 'New Hampshire Man Indicted for Sex ...',
      open_graph: [Object],
      twitter_card: [Object],
      favicon: 'https://www.justice.gov/sites/default/files/favicon.png'
    },
    id: 5e8b922aaf5ccf5ac588398c,
    text: 'New Hampshire Man Indicted',
    utcDate: '2017-01-01T12:00'
  }
]

【问题讨论】:

  • 无法从上述查询中猜测。显示一些文档以重现输出。
  • @Ashh 添加了一个示例文档。

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

$count 只会为您提供文档数量的计数,并转义所有其他内容。

因此,您必须在$facet 中再使用一个管道才能获取文档。

{ $facet: {
  metadata: [
    { $group: {
      _id: null,
      total: { $sum: 1 },
      totalArrested: { $sum: "$arrestCount" }
    }},
    { $project: {
      total: 1,
      totalArrested: 1,
      page: page,
      limit: 30,
      hasMore: { $gt: [{ $ceil: { $divide: ["$total", 30] }}, page] }
    }}
  ],
  kids: [{ $skip: (page-1) * 30 }, { $limit: 30 }]
}}

【讨论】:

  • 非常好。我必须使用 AddFields 才能使其工作。 { $addFields: { page: page, limit: 30, hasMore: { $gt: [{ $ceil: { $divide: ["$total", 30] }}, page] } }}, { $project: {总计:1,totalArrested:1,totalRescued:1,页面:1,限制:1,hasMore:1,}}
猜你喜欢
  • 1970-01-01
  • 2018-10-21
  • 2023-01-13
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
  • 2015-11-13
  • 2020-02-06
  • 2014-05-27
相关资源
最近更新 更多