I'm trying to compare, sort, filter, etc. arrays of MongoDB ObjectIDs as well as sort documents based on an arrays. My main question is: should I use ObjectID.equals()
or is it okay to convert them all to strings, use native comparisons like indexOf
, and convert them back? Does it matter?
My specific use case: a user can save posts to a list. I save this as an array of ObjectIDs user.saves
. I want to retrieve the first 25 posts in order, so I query {_id: {$in: user.saves.slice(0, 25)}}
. How would you sort retrieved documents?
solution:
db.collection.find({
$or: [{
_id: _id1
}, {
_id: _id2
}]
}, callback)
The purpose of the ObjectId in Mongodb is to uniquely identify a document. You should never need use it for sorting operations, certainly by not converting to a string.
If all you want to do is get a list of documents sorted by the time they were created. You should add created_at (timestamp) field, you can use this to sort the documents when you need to.
If you don't want to add the extra field. The ObjectId contains timestamp component, so you could extract this and use that for sorting. But the common way is to add the extra field.