简体   繁体   English

Meteor:如何按以下方式对用户进行排序?

[英]Meteor: how to sort users by most following?

welcom ... 欢迎...

I have in my Meteor project 2 collections 我的Meteor项目中有2个系列

1 - followers 1 - 粉丝

"_id": "_id",
  "follower": "username1",
  "following": "username2"
}

2- users 2-用户

"_id": "_id",
  "username": "username",
  [...]
}

I would like to sort users by the most following how I can do this 我想按照以下方式对用户进行排序

can anyone help me ?.... 谁能帮我 ?....

I would suggest putting the 'followers' collection as an object inside each 'users' document. 我建议将“粉丝”集合作为对象放在每个“用户”文档中。 There's no point in putting them in separate collections and then having to reference back and forth based on a user's ID. 将它们放在单独的集合中然后必须根据用户的ID来回引用是没有意义的。 It's just taking up more space in your DB. 它只占用了数据库中的更多空间。 Just make an object inside each user called 'follows' or something similar with the same structure (though make 'follower' and 'following' arrays). 只需在每个用户中创建一个名为'follow'的对象或类似的具有相同结构的对象(尽管make' follower'和'follow'数组)。 Something like this: 像这样的东西:

"users":{
    "_id":_id,
    "username":"username",
    "follows":{
        "followers":["username 1","username 2"],
        "following":["username 3", "username 4"],
    }
}

Once you have it so each user document has it's own 'follows' object, you can sort users by using the 'aggregate' functionality MongoDB Aggregate . 一旦拥有它,以便每个用户文档都有自己的“跟随”对象,您就可以使用MongoDB Aggregate的“聚合”功能对用户进行排序。 This following code sorts based on the length of the followers array. 以下代码根据关注者数组的长度进行排序。 You'd do a separate one for 'following' swapping out '$followers' with "$following". 你要做一个单独的'跟随'用'$ follow'换掉'$ followers'。

db.users.aggregate(
   [
      {
         $project: {
           "length": { $size: "$followers" }
         },
         { "$sort": { "length": -1 } },
      }
   ]
)

This will probably require some tweaking, of course. 当然,这可能需要一些调整。 just helping lead you in the right direction. 只是帮助引导您朝着正确的方向前进。

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

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