MongoDB 如果字段为假,则简单聚合排除记录
MongoDB Simple Aggregation Exclude Record if Field is False
如果布尔值 'active' 字段为假,我如何从聚合查询中排除整条记录?
user.aggregate([
{
'$search': {
'index': 'search-index',
'text': {
'query': searchTerm,
'path': 'name'
}
}
}, {
'$project': {
'active': {
'$filter': {
'cond': {
'$ne': [
'$active', false
]
}
}
},
'createdAt': 1,
'email': 1,
'id': 1,
'avatar': 1,
'name': 1,
'username': 1,
}
}, {
'$sort': {
'createdAt': -1
}
}, {
'$skip': skip
}, {
'$limit': limit
}
])
我已经尝试了上面的很多变体,但都没有成功。非常感谢任何帮助!干杯,雷蒙
$filter
运算符不适合您的情况。因为它用于过滤数组字段中的文档。
相反,您需要一个 $match
阶段并将其放在第一阶段。
user.aggregate([
{
$match: {
$expr: {
$ne: [
"$active",
false
]
}
}
},
... // Following stages
])
或相当于:
user.aggregate([
{
$match: {
active: true
}
},
... // Following stages
])
如果布尔值 'active' 字段为假,我如何从聚合查询中排除整条记录?
user.aggregate([
{
'$search': {
'index': 'search-index',
'text': {
'query': searchTerm,
'path': 'name'
}
}
}, {
'$project': {
'active': {
'$filter': {
'cond': {
'$ne': [
'$active', false
]
}
}
},
'createdAt': 1,
'email': 1,
'id': 1,
'avatar': 1,
'name': 1,
'username': 1,
}
}, {
'$sort': {
'createdAt': -1
}
}, {
'$skip': skip
}, {
'$limit': limit
}
])
我已经尝试了上面的很多变体,但都没有成功。非常感谢任何帮助!干杯,雷蒙
$filter
运算符不适合您的情况。因为它用于过滤数组字段中的文档。
相反,您需要一个 $match
阶段并将其放在第一阶段。
user.aggregate([
{
$match: {
$expr: {
$ne: [
"$active",
false
]
}
}
},
... // Following stages
])
或相当于:
user.aggregate([
{
$match: {
active: true
}
},
... // Following stages
])