Reputation: 178
I have a collection with users. I want to find a random collection, except mine.
db.mycoll.aggregate([{ $sample: { size: 1 } }])
This can return my document.
User.aggregate([
{ $match: { _id: { $nin: myID } } },
{ $sample: { size: 1 } }
])
Is this efficient for a really big collection?
Upvotes: 0
Views: 2185
Reputation: 4435
Looking at the stages of your aggregation pipeline:
{ $match: { _id: { $nin: myID } } }
Pipeline Sequence Optimization
This will use the built-in index on _id.
{ $sample: { size: 1 } }
This will select a sample record from the result of $match stage.
This is expected to be efficient provided not a not large size myID array.
Note:The inequality operator $nin is not very selective since it often matches a large portion of the index. As a result, in many cases, a $nin query with an index may perform no better than a $nin query that must scan all documents in a collection
Upvotes: 1