简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM