Sort By length of array mongodb query

让人想犯罪 __ 提交于 2019-12-24 01:36:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!