sanyassh
sanyassh

Reputation: 8550

Pymongo aggregate() sort an array field

I am doing an aggregate and on some stage i have following results:

[{ "_id" : 1, "array_field": [1, 2, 3]},
 { "_id" : 2, "array_field": [3, 2, 1]}]

I want to get the array_field sorted on next stage:

[{ "_id" : 1, "array_field": [1, 2, 3]},
 { "_id" : 2, "array_field": [1, 2, 3]}]

What is the possibilities? The $sort didnt helped me.

Upvotes: 1

Views: 2427

Answers (1)

Ashh
Ashh

Reputation: 46491

You need to $unwind the array_field and then again $group to rollback

db.collection.aggregate([
  { "$unwind": "$array_field" },
  { "$sort": {
    "array_field": 1
  }},
  { "$group": {
    "_id": "$_id",
    "array_field": {
      "$push": "$array_field"
    }
  }}
])

Upvotes: 2

Related Questions