【问题标题】:Group MongoDB documents by field按字段对 MongoDB 文档进行分组
【发布时间】:2023-01-12 21:00:21
【问题描述】:

我收集了一系列如下问题 -

{
    question: "what's the question?",
    answer: "some answer",
    points: 10
},
{
    question: "what's the question again?",
    answer: "some answer again",
    points: 40
},
...

已回答的问题将在其文档中包含 answer,反之亦然。我想使用 aggregate 将所有已回答和未回答的问题分组,以获得类似的输出 -

{
  answered: [{...}, {...}],
  unanswered: [{...}, {...}]
}

这个聚合查询会是什么样子?

【问题讨论】:

    标签: mongodb aggregate


    【解决方案1】:

    有多种方法可以做到这一点。

    一种是使用 $facet,如下所示:

    db.collection.aggregate([
      {
        "$facet": {
          "answered": [
            {
              $match: {
                answer: {
                  $exists: true
                },
                
              },
              
            },
            
          ],
          "unanswered": [
            {
              $match: {
                answer: {
                  $exists: false
                },
                
              },
              
            },
            
          ],
          
        }
      }
    ])
    

    【讨论】:

      【解决方案2】:

      一种选择是使用 $group 而不是 $facet,因为 $facet 不使用索引:

      db.collection.aggregate([
        {
          $group: {
            _id: 0,
            answered: {
              $push: {
                $cond: [
                  {
                    $eq: [
                      {
                        $toBool: "$answer"
                      },
                      true
                    ]
                  },
                  "$$ROOT",
                  "$$REMOVE"
                ]
              }
            },
            unanswered: {
              $push: {
                $cond: [
                  {
                    $ne: [
                      {
                        $toBool: "$answer"
                      },
                      true
                    ]
                  },
                  "$$ROOT",
                  "$$REMOVE"
                ]
              }
            }
          }
        },
        {
          $unset: "_id"
        }
      ])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-24
        • 2020-09-08
        • 2018-03-23
        • 1970-01-01
        • 2015-09-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多