按数组长度排序mongodb查询 [英] Sort By length of array mongodb query
本文介绍了按数组长度排序mongodb查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有如下的MongoDB文档: 是否有查询以对subscribedGroups的长度对文档进行排序?可以上升或下降.
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")
]
}
推荐答案
您可以使用 $sort
以及数组的长度
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
}
}
])
请参见示例
这篇关于按数组长度排序mongodb查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文