3

Suppose I have these documents:

[
  {
    '_id': 1,
    'roles': [
      {
        'k': 'free',
        'v': 1
      },
      {
        'k': 'pro',
        'v': 5
      },
      {
        'k': 'free',
        'v': 2
      }
    ]
  },
  {
    '_id': 2,
    'roles': [
      {
        'k': 'pro',
        'v': 1
      },
      {
        'k': 'free',
        'v': 3
      },
      {
        'k': 'free',
        'v': 2
      }
    ]
  }
]

So for every _id, we have a array of documents called roles.
I need to sort inside the array roles, using the v field.

Expected output:

[
  {
    '_id': 1,
    'roles': [
      {
        'k': 'free',
        'v': 1
      },
      {
        'k': 'free',
        'v': 2
      }
      {
        'k': 'pro',
        'v': 5
      }
    ]
  },
  {
    '_id': 2,
    'roles': [
      {
        'k': 'pro',
        'v': 1
      },
      {
        'k': 'free',
        'v': 2
      }
      {
        'k': 'free',
        'v': 3
      }
    ]
  }
]

So I tried to use $sort:

{
  '$sort': {
     'roles.v': 1
  }
}

But it does not sort inside the array.

3 Answers 3

3

You need to $unwind and $group to reconstruct.

([
  { $unwind: "$roles" },
  { $sort: { "roles.v": 1 }},
  { $group: {
    _id: "$_id",
    roles: { $push: "$roles" }
  }}
])
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, this works like a charm. Thanks for this easy approach!
0

In order to sort by _id and if $project is needed, this will work as well.

db.getCollection("collectionName").aggregate([
    { $unwind: "$roles" },
    { $sort: { "roles.v": 1 }},
    { $group: {
        _id: "$_id",
        roles: { $push: "$roles" }
    }},
    {$project: {
        _id: "$_id",
        roles: "$roles"
    }},
    {$sort: {"_id": 1}}
])

Comments

0

You can use a simple mongdb method $sortArray The code is this:

db.collection.aggregate([
  {
    $project: {
      _id: 0,
      result: {
        $sortArray: {
          input: "$roles",
          sortBy: {
            v: 1
          }
        }
      }
    }
  }
])

1 Comment

if you want _id also, just make _id : 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.