MongoDB sorting documents by nested data

后端 未结 1 1194
小鲜肉
小鲜肉 2021-01-16 01:40

Considering the following design for posts:

{
title: string,
body: string,
comments: [
    {name: string, comment: string, ...},
    {name: string, comment:          


        
1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-16 02:21

    You need to use the aggregate command

    This should give you a list of post _id with the number of comments sorted by the count in reverse order.

    You can use the $limit operators to return the x top rows. e.g. { $limit : 5 }

     db.posts.aggregate(
       { $unwind : "$comments" },
       { $group : { _id : "$_id" , number : { $sum : 1 } } },
       { $sort : { number : -1 } }
     );
    

    Take a look http://docs.mongodb.org/manual/tutorial/aggregation-examples/

    0 讨论(0)
提交回复
热议问题