M
M
mozart13372016-04-25 02:02:02
MongoDB
mozart1337, 2016-04-25 02:02:02

How to select only certain elements from a nested array?

There is a document

{
  id: ObjectID(),
  mas: [{
    test: 3,
    sdfsbhfn: 1,
    sdfbhsnf: 1
  }, {
    test: 2,
    sdgfbhsdnfv: 1,
    sdhfdng: 1
  }, {
    test: 3,
    sdfsgbhfnv: 1,
    sdhfsndgfj: 3
  }]
}

The sample goes by a unique Mongolian ID. How can I make the database return objects from the contents of "mas" where "test: 3" is? I try protection $elemMatch, but it returns only the first matched element and that's it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kuznetsov, 2016-04-25
@evgentus

If in the finished selection by _id it is necessary, then only aggregation https://docs.mongodb.org/manual/core/aggregation-p...

  1. select by _id ($match)
  2. unwind array mas ($unwind)
  3. filter by test = 3 ($match)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question