我有一个收藏:
[
{
"name": "Alex",
"cars": [
{
"label": "BMW",
"age": 13,
"things": [ ... ]
},
{
"label": "Mercedes",
"age": 8,
"things": [ ... ]
}
]
},
{ ... }
]
我会过滤掉每个人things
的 s 。car
因此,获得相同的集合(具有相同的模式)但没有一些thing
s。
我如何通过 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
(因为现实世界中有很多字段)?