How to project only matching fields of a nested array into a mongo shell request

I am new to mongodb and I have that, hopefully, a simple question:

I have a nested scheme where I have a field that is an array, where each element of this array is an object that itself has an array field.

For example:

> db.mytest.insert({ name: 'a', top: [ {x:1, y:2, nest: [{p:1, q:2}, {p:2, q:3}]}, {x:2, y:3, nest: [{p:4, q:5}, {p:6, q:7}]} ] }) 

I can request specific p values ​​just fine and can even limit my result to the first matching top element:

 > db.mytest.findOne({'top.nest': {$elemMatch: {p:6}}}, {'top.nest.$': 1}) {"_id":ObjectId(...), top: [{x:2, y: 3, nest: [{p:4, q:5}, {p:6, q:7}]}]} 

This brings me to my question: {'top.nest.$': 1} and {'top.$': 1} , since my projection document returns the same result. How to limit search results to include only the first nest matching element?

Do I need a second pass that iterates over the result of this query style?

+7
arrays mongodb
source share
1 answer

Well, the trick was the aggregation structure, specially untwisted .

 > db.mytest.aggregate({$unwind: '$top'}, {$unwind: '$top.nest'}, {$match: {'top.nest.p': 6}} ) 

Although in the case when I had several auxiliary matches in one object, this would return several results instead of their original grouped form. I suppose I can put $group in the pipeline.

Although the related links I found suggested redesigning the circuit as the only complete fix right now, so it's definitely better than nothing.

+6
source share

All Articles