A
A
Alexander Kurakin2016-09-15 21:13:09
MongoDB
Alexander Kurakin, 2016-09-15 21:13:09

How to filter an array at each array element of a MongoDB collection?

There is a collection:

[
  {
    "name": "Alex",
    "cars": [
      {
        "label": "BMW",
        "age": 13,
        "things": [ ... ]
      },
      {
        "label": "Mercedes",
        "age": 8,
        "things": [ ... ]
      }
    ]
  },
  { ... }
]

We need to get a collection without some `thing`s, by condition, using MongoDB aggregations.
Wrote code:
db.matches.aggregate([{
  $project: {
    '_id': '$_id',
    'cars': {
      $map: {
        input: '$cars',
        as: 'car',
        in: {
          'things': {
            $filter: {
              input: '$$car.things',
              as: 'thing',
              cond: {
                $lte: [ '$$thing.cost', 10 ]
              }
            }
          }
        }
      }
    }
  }
}
])

But it requires an explicit enumeration of all stored fields, the list of which in the real collection varies (is unknown). How to be?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2016-12-02
@kuraga333

Maybe $redact will help you ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question