简体   繁体   English

使用 Mongoose 根据数组的大小对结果进行排序

[英]Sort a result according to the size of an array with Mongoose

I'm using MongoDB (mongoose), and I'm looking to sort the elements by Array size (descending order).我正在使用 MongoDB (猫鼬),我希望按数组大小(降序)对元素进行排序。 I've tried a lot of things, but I don't understand how it works.我已经尝试了很多东西,但我不明白它是如何工作的。 I'd like to avoid sorting the results manually (I mean with the JS), I'd rather have MongoDB do it.我想避免手动对结果进行排序(我的意思是使用 JS),我宁愿让 MongoDB 这样做。 Can you help me please?你能帮我吗?

Here is my code:这是我的代码:

users = await userModel.find({ UserStatus: "Success" })
  .sort({ "Progression.Room.RoomActorLikes": { "length": -1 } })
  .skip((request.pageindex) * request.pagesize)
  .limit(request.pagesize);

Here is an example that could be the first result:这是一个可能是第一个结果的示例:

The second would be:第二个是:

And so on...等等...

Thank you in advance for your answer!预先感谢您的回答!

What about this:那这个呢:

        db.collection.aggregate([  { $addFields:{ len:{$size:"$room.RoomActorLikes"}}}    , {$sort:{len:-1}} ,{$skip: skip},
{$limit: limit}  ])

Detailed example:详细示例:

       db.collection.aggregate([
      {
        $match: {
              UserStatus: "Success"
                }
      },
      {
       $addFields: {
             len: {
              $size: "$room.roomActorLikes"
                  }
             }
      },
      {
        $sort: {
              len: -1
               }
       },
       {
          $skip: 1
        },
       {
          $limit: 3
       },
       {
          $project: {
                   len: 0
                    }
       }
      ])

explained:解释:

  1. $match -> Here reduce the amount of documents down to the ones that are with UserStatus-> Success in $match stage or if there is more conditions better so the amount of documents that need to be processed in later stages to be smaller. $match -> 这里将文档数量减少到 $match 阶段的 UserStatus-> Success 或如果有更多条件更好,因此需要在后期处理的文档数量更少。 ( Best is to have index on this field so if you have too many documents this to reduce the processing as much as possible ) (最好是在这个字段上有索引,所以如果你有太多的文档,尽可能减少处理)

  2. $addFields -> Create new field len that will contain the number of array elements in document array to be easy to sort later. $addFields -> 创建新的字段 len,它将包含文档数组中数组元素的数量,以便以后排序。

  3. $sort -> Sort in descending order ithe documents based on array counts. $sort -> 根据数组计数对文档进行降序排序。

  4. $skip the number of documents to display as part of your paging action. $skip 作为分页操作的一部分显示的文档数。

  5. $limit the number of ducuments to display as part of your paging action. $limit 作为分页操作的一部分显示的文件数。

  6. $project to remove the len field if you dont need in the final output ( this is optional since you may not consider it from the app side ) $project 如果您在最终 output 中不需要删除 len 字段(这是可选的,因为您可能不会从应用程序方面考虑)

playground操场

Abit more safer option $addFields->$size, preventing error messages in case of missing RoomActorlikes or missing room field from the main document:升技更安全的选项 $addFields->$size,防止在缺少 RoomActorlikes 或主文档中缺少房间字段的情况下出现错误消息:

          {
           $addFields: {
          len: {
    $size: {
      $cond: {
        if: {
          $eq: [
            {
              $type: "$room.roomActorLikes"
            },
            "missing"
          ]
        },
        then: [],
        else: "$room.roomActorLikes"
        }
       }
     }
    }
   }

playground safe option ( checking if RoomActorLikes exist )游乐场安全选项(检查 RoomActorLikes 是否存在)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM