Question

If I have a collection similar to:

[
    { "test": [ { "a": 1, "b": 2 }, { "a": 10, "b": 1 } ] },
    { "test": [ { "a": 5, "b": 1 }, { "a": 14, "b": 2 } ] },
    ...
]

How do I obtain only a subset of data consisting of the a values when b is 2? In SQL, this would be something similar to:

SELECT test.a FROM collection WHERE test.b = 2

I do understand that I can limit what data I get with something like:

collection.find({ }, { "test.a": 1 })

But that returns all the a values. How can I limit it so that it returns only the values in which b is 2 (the WHERE test.b = 2 part of the SQL equivalent)?

Was it helpful?

Solution

You can do this by adding a selector object as the first parameter of your find call and using the $elemMatch projection operator:

collection.find({ 'test.b': 2 }, { test: { $elemMatch: { b: 2 } }, 'test.a': 1 })

But this will only return the first test array element per-doc where b is 2. You would need to use the aggregation framework if there can be multiple b:2 elements in your test arrays.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top