I have two collections like
Business = {
_id : ObjectID,
name: string
}
and
Features ={
bid: ObjectID // it is _id of businesses
features: Array of string
}
And I need to build query that find all businesses with special feature.
First solution is to do 2 queries: first query is features.Find(features:“my_feature”) and second to get all businesses with _id from list, that I get on first step.
Second solution is to build single query with $lookup and $match.
But I don`t know what is best solution for such situation.
I came from RDMS, where such problem usually is solved by single query like
SELECT * FROM businesses INNER JOIN features ON businesses._id=features.bid
WHERE ‘my_feature’ IN features.features
I would go with aggregation solution (see example below).
It may require a bit more RAM for $unwind and $replaceRoot stages, but the result can be achieved faster using only 1 request to the database.