我有一个名为User的集合。每个用户都包含如下文档所示的数据。我想得到一个有历史数据的用户,但历史数组应该只包含数组中的活动记录。
{
"_id" : ObjectId("62f1df89fd621s2c419e5d47"),
"name" : "Test User",
"createDate" : ISODate("2022-08-25T04:43:33.949Z"),
"history" : [
{
"departmentName" : "department1",
"active" : false
},
{
"departmentName" : "department2",
"active" : true
},
{
"departmentName" : "department3",
"active" : false
}
],
"updateDate" : ISODate("2022-08-25T05:26:53.281Z")
}
这是我想要的输出:
{
"_id" : ObjectId("62f1df89fd621s2c419e5d47"),
"name" : "Test User",
"createDate" : ISODate("2022-08-25T04:43:33.949Z"),
"history" : [
{
"departmentName" : "department2",
"active" : true
}
],
"updateDate" : ISODate("2022-08-25T05:26:53.281Z")
}
尝试了以下查询,但无法获得预期结果
db.getCollection('users')
.aggregate([{
$match : {'name' : 'Test User','history.active' : true}
}])
您只需要使用$filter过滤histroy
数组,如下所示:
db.collection.aggregate([
{
$match: {
"name": "Test User",
"history.active": true
}
},
{
$addFields: {
history: {
$filter: {
input: "$history",
cond: {
$eq: [
"$$this.active",
true
]
}
}
}
}
}
])
Mongo游乐场