We have a collection of user submitted posts in MongoDB and they can be 'starred' by other users. I'm wondering what the best way to achieve this is?
My first guess would be to put an array of user id's on a post that have starred it like so:
{
created:Date
title:String
content:String
...
starred_by:[ObjectId] // Array of users by id that have starred the post
}
Then when we do a find() I would like to order by:
$sort: {
starred_by:{$in:[session.user_id]},
created:-1
}
Is this possible? I'm struggling to find any docs on it. We really want the results of the find first ordered by the 'starred_by' field, so that starred results come first, then secondly ordered by creation date.
Thanks
I suggest that you put them into a separate collection
{ item : ObjectID, user: ObjectID, starred_on : Date }
The reason is that an item may potentially be starred by a lot of users and that your item document might outgrow the document limit size (16MB).
I'm not entirely sure what your query does (show the newest articles starred by a given user?). In case you want to show the latest items starred by a given user (mongodb shell):
db.starred.find({ user : session.user_id, }).sort([starred_on, -1])