Skip to content

Instantly share code, notes, and snippets.

@includeamin
Created June 1, 2019 17:27
Show Gist options
  • Save includeamin/d6fa291904a1218dca43f655a4221234 to your computer and use it in GitHub Desktop.
Save includeamin/d6fa291904a1218dca43f655a4221234 to your computer and use it in GitHub Desktop.
Sort array in pymongo (mongodb) depends on specific field in array
data = {"_id":"5c62ff5cdc6e89000ac76dc8"
,"Answers":[
{"Text":"text1","Point":2},
{"Text":"text2","Point":1},
{"Text":"Hallo","Point":3}
]
a = db.aggregate(
[ {"$match":{"_id":objectid.ObjectId("5c62ff5cdc6e89000ac76dc8")}},
{ "$unwind": '$Answers'},
{"$match":
{'Answers.Text': {"$regex": "^" + "t"}}
},
{"$sort": {
'Answers.Point': -1
}}]
)
@includeamin
Copy link
Author

output

  {"Text":"Hallo","Point":3}
   {"Text":"text1","Point":2}
   {"Text":"text2","Point":1}
  

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment