Reputation: 1
I have collection A having reference of collection B. Few documents of A may not contain B reference. A[ { _id:1 Name:"abc" B: DBRef('B','4sd567fgv5b78n899') }, { _id:2 Name:"def" } ]
B{ _id: ObjectId('4sd567fgv5b78n899') Type:"alpha" }
I have to fetch all A where either B is not present or if present fetch only those where B.Type=="alpha". My application have Mongo Template and mongoRepository.
I tried to fetch all id 1st from B collection where B.Type=="alpha" and then using orOperator fetched records from A collection where B is null or A.B in (All id's fetched from above query). It's taking approx 7s to fetch 10k records which is not feasible and also the way I'm fetching data is not proper way.
Upvotes: 0
Views: 344
Reputation: 479
You can use the lookup in aggregation to fetch data from reference document. You also need to keep in mind that you have added appropriate indexes if you are having performance issues.
db.A.aggregate(
{$lookup: {
from:"B",
localField: "_id",
foreignField: "_id",
as: "bdoc"
}},
{$match: {
"bdoc.type": "alpha"
}}
)
Upvotes: 0