Home > Blockchain >  mongoDB aggregation- unwind, sort and group
mongoDB aggregation- unwind, sort and group

Time:02-02

Considering I have a users collection contains those documents:

        {
          _id: 1,
          hobbies: ['eat', 'read', 'swim']
        },
        {
          _id: 2,
          hobbies: ['eat', 'sleep', 'swim']
        },
        {
          _id: 3,
          hobbies: ['code', 'read', 'eat']
        }

I want to do an aggregation on this collection so the result will be a distinct list of all those hobbies sorted in alphabetic order, for example:

    {
      result: [code, eat, read, sleep, swim] 
    }

I've tried this solution, but it didn't work for me:

    {
      $unwind: {path: "$hobbies"},
      $group: {_id: null, result: {$addToSet: "$hobbies"}}
    }

My problem is to sort the result field...

CodePudding user response:

Your approach is very close already. Just remember $unwind and $group are separate pipeline stages. You need to wrap them with individual curly brackets. And for the sorting, you can do a $sortArray at the end of the pipeline.

db.collection.aggregate([
  {
    $unwind: {
      path: "$hobbies"
    }
  },
  {
    $group: {
      _id: null,
      result: {
        $addToSet: "$hobbies"
      }
    }
  },
  {
    $set: {
      result: {
        $sortArray: {
          input: "$result",
          sortBy: 1
        }
      }
    }
  }
])

Mongo Playground

  • Related