I do not clearly understand what does $limit in aggregate. I'm using aggregate because I need to populate my item, but I can't do it in a findOne (don't know why, but it always return nothing).
return Item.aggregate(
[
{ $match: { _id: mongoose.Types.ObjectId(id) } },
{ $limit: 1 },
{
$lookup: {
from: 'variations',
localField: '_id',
foreignField: 'item',
as: 'variations'
}
}
]
).then(result => { console.log(result) });
In this case, is fetching stop when one result match, or is $limit just keep one item from the total result ? In the second case, how can I stop fetching when an item is matching ?
$limit is used to restrict the number of items passed through to the next stage in an aggregation pipeline. say your $match stage selected records by { status : 'active' }
and it produced 1 million records and you only need the top 10 records passed to the next stage or to return those 10 records to the client then you'd add a { $limit : 10 }
stage.
but in your case, since you're matching by objectId, you don't need the $limit stage because objectIds are unique and there will only ever be a single record with that Id. so you can remove it.
also you cannot use the find
interface for retrieval because it doesn't allow you to do joins/lookups with another collection. find interface is for directly retrieving records from a single collection. so you need to use the aggregation framework for scenarios such as lookups.