Search code examples
mongodbmongoosegroupingmongoose-schema

MongoDB - group documents by field value


I need to group following documents by featured and trending.

[
    {
        "_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")
    }
]

So, after grouping they should be in following format -

[
    {
        _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")
            }
        ]
    }
]

How can I get this result through aggregation or any other way?

I have been trying with aggregate $group. But I can't figure out how can I $group via featured/trending value with equal true.

So, I don't need corresponding false value when grouping them. Also, there might have other fields like highlighted etc along with featured trending.


Solution

  • This is quite easy to achieve, the easiest way to do it is using $facet

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

    MongoPlayground