0

我有一个收藏:

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

我会过滤掉每个人things的 s 。car因此,获得相同的集合(具有相同的模式)但没有一些things。

我如何通过 MongoDB 聚合来做到这一点?

UPD:“可能重复”解释了如何过滤子数组而不是其中的子子数组(AFAIK)。

UPD2:我写了一些过滤子子数组的代码,但我应该指出我想要保存的所有字段......

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 ]
              }
            }
          }
        }
      }
    }
  }
}
])

person问题:我可以自动为s 和他们的 s保留其他字段car(因为现实世界中有很多字段)?

4

0 回答 0