Mongodb 我是否可以在Mongo聚合框架中的match命令上创建替代条件?
在命令中(在MongoDB聚合框架中);如果没有任何匹配项,是否有方法创建替代条件?考虑到以下几点: 国家/地区系列Mongodb 我是否可以在Mongo聚合框架中的match命令上创建替代条件?,mongodb,aggregation-framework,Mongodb,Aggregation Framework,在命令中(在MongoDB聚合框架中);如果没有任何匹配项,是否有方法创建替代条件?考虑到以下几点: 国家/地区系列 [ { "name": "Afghanistan", "countryCode": "AF" }, { "name": "United States",
[
{
"name": "Afghanistan",
"countryCode": "AF"
},
{
"name": "United States",
"countryCode": "US"
}
]
我认为这会将countryCode
与“我们”匹配,因为“否”与以下任一文档都不匹配:
db.countries.aggregate([
{
$match: {
$expr: {
$ifNull: [
{
$eq: [
"$countryCode",
"NO"
]
},
{
$eq: [
"$countryCode",
"US"
]
}
]
}
}
}
])
我可以通过以下方法实现这一点,但它感觉不整洁,并通过管道推送不必要的文档
感谢您的帮助
db.countries.aggregate([
{
$group: {
"_id": null,
"countries": {
$push: "$$ROOT"
}
}
},
{
$project: {
"countries": 1,
"country": {
$filter: {
"input": "$countries",
"as": "cot",
"cond": {
$eq: [
"$$cot.countryCode",
"NO"
]
}
}
}
}
},
{
$project: {
"country": {
$cond: {
"if": {
$gt: [
{
$size: "$country"
},
0
]
},
"then": "$country",
"else": {
$filter: {
"input": "$countries",
"as": "cot",
"cond": {
$eq: [
"$$cot.countryCode",
"US"
]
}
}
}
}
}
}
},
{
"$unwind": "$country"
}
])