简体   繁体   English

流星和MongoDB通过两个子对象对Collection进行排序

[英]Meteor and MongoDB sort Collection by two sub objects

I want to sort an unread message collection by user and message timestamp. 我想按用户和消息时间戳排序未读消息集合。 I'd like all messages to be grouped by the users where the messages are most recent. 我希望所有消息都按最新消息的用户分组。 I've tried the following: 我尝试了以下方法:

UnreadMessages.find({},
   {sort: {'message.timestamp': -1, 'fromUser._id': 1} });

However, that doesn't group up messages by user. 但是,这不会按用户对邮件进行分组。

Is there a better way to show most recent messages at the top grouped by user? 有没有更好的方法可以按用户分组显示最新消息? Thank you. 谢谢。

Your code will do the opposite of what you want. 您的代码将执行与您想要的相反的操作。

If it was MongoDB, you really should be doing 如果是MongoDB,您确实应该这样做

UnreadMessages.find({},
   {sort: { 'fromUser._id': 1, 'message.timestamp': -1 } });

instead. 代替。 But Minimongo doesn't work like that. 但是Minimongo不能那样工作。

There is a new feature that just got commited , which allows you to specify your own comparator function. 刚刚提交一个新功能,它允许您指定自己的比较器函数。 I haven't tried it myself, but you should be able to do 我自己还没有尝试过,但是您应该可以

function myComparatorFn( a, b ) {
   // Standard comparator procedure: return -1 if a < b, 0 if a == b, 1 if a > b
}

UnreadMessages.find({}, {sort: myComparatorFn });

However, if I read the commit log correctly, it looks like this commit just barely missed the 1.3.3 release :-( 但是,如果我正确地阅读了提交日志,则看起来该提交几乎没有错过1.3.3版本:-(

An alternative more elaborate solution would be to use something like https://atmospherejs.com/zvictor/mongodb-server-aggregation and then run a MongoDB aggregation pipeline with $group on the server. 另一种更详尽的解决方案是使用类似https://atmospherejs.com/zvictor/mongodb-server-aggregation的内容 ,然后在服务器上运行带有$ group的MongoDB聚合管道。

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

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