简体   繁体   中英

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

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

instead. But Minimongo doesn't work like that.

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 :-(

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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