希望我理解正确,
-
$group by url 并将所有内容存储在 root 字段中
db.collection.aggregate([
{
$group: {
_id: "$url",
status: {
$push: "$status"
},
root: {
$push: "$$ROOT"
},
count: {
$sum: 1
}
}
},
-
$match 所有不等于400 的元素使用$ne 和$not 与$ne 进行相反匹配,这意味着等于400
/** MATCH ALL HAVE 400 STATUS*/
{
$match: {
"status": {
$not: {
$elemMatch: {
$ne: "400"
}
}
}
}
},
-
$unwind root 变量并使用 $replaceRoot 替换为根目录
{
$unwind: "$root"
},
{
$replaceRoot: {
newRoot: "$root"
}
},
-
$group url 用于删除相同状态的重复项,创建新变量 roots 并存储“$$ROOT”
{
$group: {
_id: "$url",
roots: {
$first: "$$ROOT"
}
}
},
{
$replaceRoot: {
newRoot: "$roots"
}
}
])
结果:
[
{
"_id": 4,
"status": "400",
"url": "c"
},
{
"_id": 3,
"status": "400",
"url": "b"
}
]
工作场所:
https://mongoplayground.net/p/C6tC8ho1t6M