Home > Software design >  How do I use $unwind and then $group in the same mongodb query
How do I use $unwind and then $group in the same mongodb query

Time:04-03

I have the following mongodb structure...

[
    {
        track: 'Newcastle',
        time: '17:30',
        date: '22/04/2022',
        bookmakers: [
            {
                bookmaker: 'Coral',
                runners: [
                    {
                        runner: 'John',
                        running: true,
                        odds: 3.2
                    },
                    ...
                ]
            },
            ...
        ]
    },
    ...
]

I'm trying to find filter the bookmakers array for each document to only include the objects that match the specified bookmaker values, for example:

{ 'bookmakers.bookmaker': { $in: ['Coral', 'Bet365'] } }

At the moment, I'm using the following mongodb query to only select the bookmakers that are specified, however I need to put the documents back together after they've been seperated by the '$unwind', is there a way I can do this using $group?

await HorseRacingOdds.aggregate([
    { $unwind: "$bookmakers" },
    {
        $group: {
            _id: "$_id",
            bookmakers: "$bookmakers"
        }
    },
    {
        $project: {
            "_id": 0,
            "__v": 0,
            "lastUpdate": 0
        }
    }
])

CodePudding user response:

How about a plain $addFields with $filter?

db.collection.aggregate([
  {
    "$addFields": {
      "bookmakers": {
        "$filter": {
          "input": "$bookmakers",
          "as": "b",
          "cond": {
            "$in": [
              "$$b.bookmaker",
              [
                "Coral",
                "Bet365"
              ]
            ]
          }
        }
      }
    }
  },
  {
    $project: {
      "_id": 0,
      "__v": 0,
      "lastUpdate": 0
    }
  }
])

Here is the Mongo playground for your reference.

  • Related