问题
I have MongoDB document like below: is there a query to Sort the documents with the length of subscribedGroups? which can be ascending or descending.
{
"_id" : ObjectId("58c29d9ec79d585c0e16b110"),
"subscribedGroups" : [
ObjectId("5b28a9190c8c0d0014b03a0c"),
ObjectId("5b2930650b813a0014a3294d"),
ObjectId("5b29f1b5243d470014d6d351")
]
}
回答1:
You can find the size of the subscribedGroups
using $size and then easily $sort with the length of the array
db.collection.aggregate([
{
$addFields: {
subscribedGroupsLength: {
$size: "$subscribedGroups"
}
}
},
{
$sort: {
subscribedGroupsLength: -1
}
}
])
See the sample
来源:https://stackoverflow.com/questions/50942173/sort-by-length-of-array-mongodb-query