MongoDb在聚合$project中排除null
我在MongoDb中收集了以下形状的数据:MongoDb在聚合$project中排除null,mongodb,mongodb-aggregation,Mongodb,Mongodb Aggregation,我在MongoDb中收集了以下形状的数据: [{ "_id": "1", "Sq1" : 5, "Sq1comment" : "In general you aaaaaa.", "Sq2" : 8, "S2comment" : null, "Sq3" : 5, "Sq3comment" : "A person bbbbb." }, { "_id": "2", "Sq1" : 4, "Sq1comment" : "In general you c
[{ "_id": "1",
"Sq1" : 5,
"Sq1comment" : "In general you aaaaaa.",
"Sq2" : 8,
"S2comment" : null,
"Sq3" : 5,
"Sq3comment" : "A person bbbbb."
},
{ "_id": "2",
"Sq1" : 4,
"Sq1comment" : "In general you cc.",
"Sq2" : 8,
"S2comment" : "A story ff",
"Sq3" : 5,
"Sq3comment" : null
}
]
我想提取“comment”字段,但只反映结果中不为空的字段
我可以通过查询逐个提取字段(Sq1comment;Sq2comment,Sq3comment)
db.collection.find({ "Sq1comment": { $not: { $type: 10 } })
其输出为:
[{ "_id": "1",
"Sq1comment" : "In general you aaaaaa.",
"Sq3comment" : "A person bbbbb."
}]
或者,如果我执行聚合$project,则“注释”字段中的所有空值都存在:
db.collection.aggregate([{$project:
{ "Sq1comment": "$Sq1comment",
"Sq2comment": "$Sq2comment",
"Sq3comment": "$Sq3comment"
} }])
其输出为:
[{ "_id": "1",
"Sq1comment" : "In general you aaaaaa.",
"S2comment" : null,
"Sq3comment" : "A person bbbbb."
},
{ "_id": "2",
"Sq1comment" : "In general you cc.",
"S2comment" : "A story ff",
"Sq3comment" : null
}
]
我希望一个项目的数据显示所有的评论字段,但只有不为空的条目。因此,排除空字段就是聚合。也许您可以尝试
$unwind
,然后$group
来获得您想要的结果
像这样:
{
$unwind:
{
path: <field path>,
includeArrayIndex: <string>,
preserveNullAndEmptyArrays: <boolean>
}
}
{
$REWIND:
{
路径:,
INCLUDEARAYINDEX:,
保留Null和EmptyArray:
}
}
preservenallandemptyarray
将帮助排除空数组
更多可访问的链接: