In my MongoDB collection I have a documents that follow a parent-child structure.
Each parent doc typically has 4 fields, with the children having 3 (no group field).
parent:
{
_id: doc_123
parent_id: 123
active: true
group: A
}
children
{
id: doc_123_1
parent_id: 123
active: true
}
{
id: doc_123_2
parent_id: 123
active: true
}
I want to write a BSON query / aggregation if needed for my Java Spring project that will return all the docs that match the following fields provided by user:
- active field – this will be true or false
- group field – e.g "A"
My difficulty is that each child document is assumed to have the same value as the parent for the group field, but it is not actually in the document.
How can I write a query that will match all the parent and child documents for a certain group?
All documents are in the one collection, there are no separate collections for parent and child docs.
2
Answers
Aggregation steps:
group
andactive
true/false based on the user-provided values.parent_id
to self-lookup into the same collection and match onparent_id
parent_id
is identical for children and the parent.doc_123
for parents anddoc_123_1
,doc_123_2
for children will be very non-performant for actual search/match/lookups.id
in children calledid
or_id
? But it doesn’t affect the pipeline here.Mongo Playground
Join to parents adding a condition of group on the join:
See live demo.