我在mongo中收集了文档。
{
_id: "1",
name: "test1",
active: true,
cars: [
{ _id: "2", name: "aaa", active: true },
{ _id: "3", name: "bbb", active: false },
{ _id: "4", name: "ccc", active: true },
},
{
_id: "2",
name: "test2",
active: false,
cars: [
{ _id: "10", name: "aaa", active: true }
}
我只想返回活动项目。在此示例中:
{
_id: "1",
name: "test1",
active: true,
cars: [
{ _id: "2", name: "aaa", active: true },
{ _id: "4", name: "ccc", active: true },
}
我该怎么做?
需要使用聚合管道来$filter
非活动数组元素
db.col.aggregate([
{$match : {"active" : true}},
{$addFields : {
cars : {
$filter : {
input : "$cars",
as : "c",
cond : "$$c.active"}
}
}}
])
结果
> db.col.aggregate([{$match : {"active" : true}},{$addFields : {cars : {$filter : {input : "$cars", as : "c", cond : "$$c.active"}}}}]).pretty()
{
"_id" : "1",
"name" : "test1",
"active" : true,
"cars" : [
{
"_id" : "2",
"name" : "aaa",
"active" : true
},
{
"_id" : "4",
"name" : "ccc",
"active" : true
}
]
}