MongoDB - 按字段值分组文档

3
我需要按照“推荐”和“热门”将以下文档分组。
[
    {
        "_id" : ObjectId("5f22546cd49ffe0d6f087a2e"),
        "title" : "....",
        "image" : "...",
        "featured" : true,
        "trending" : false,
        "creationDate" : ISODate("2020-07-30T05:02:36.592Z")
    },
    {
        "_id" : ObjectId("5f22546cd49ffe0d6f087a2f"),
        "title" : "Cras non dolor",
        "image" : "...",
        "featured" : false,
        "trending" : true,
        "creationDate" : ISODate("2020-07-30T05:02:36.592Z")
    }
]

那么,在分组后,它们应该呈以下格式 -

[
    {
        _id: null,
        featured: [
            {
                "_id" : ObjectId("5f22546cd49ffe0d6f087a2e"),
                "title" : "....",
                "image" : "...",
                "featured" : true,
                "trending" : false,
                "creationDate" : ISODate("2020-07-30T05:02:36.592Z")
            }
        ],
        trending: [
            {
                "_id" : ObjectId("5f22546cd49ffe0d6f087a2f"),
                "title" : "Cras non dolor",
                "image" : "...",
                "featured" : false,
                "trending" : true,
                "creationDate" : ISODate("2020-07-30T05:02:36.592Z")
            }
        ]
    }
]

我该如何通过聚合或其他方式获得此结果?
我一直在试用聚合的 $group,但我不知道如何按 featured/trending 的值为 true 进行分组。所以,在对它们进行分组时,我不需要相应的 false 值。此外,可能会有其他字段,如 highlighted 等,与 featured trending 一起出现。
1个回答

4

这很容易实现,最简单的方法是使用$facet

db.collection.aggregate([
  {
    $facet: {
      featured: [
        {
          $match: {
            "featured": true
          }
        }
      ],
      trending: [
        {
          $match: {
            "trending": true
          }
        }
      ]
    }
  }
])

MongoPlayground

的翻译结果是:

{{链接1:MongoPlayground}}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接