我的建议是排除已与MongoDb中先前的匹配聚合匹配的记录。
在第一场比赛中,我需要从两个国家(美国和德国)获取记录。
在第二场比赛中,我需要排除给定国家/地区的记录,例如美国AND级别的“ Begginer”,但保留来自美国和德国的其他记录。那怎么可能? 示例数据:
[
{
country: 'United States',
personName: 'John',
level: 'Average',
},
{
country: 'United States',
personName: 'Rina',
level: 'Begginer',
},
{
country: 'Germany',
personName: 'John',
level: 'Average',
}
]
首场比赛(正确):
{
country: {$in: ['United States', 'Germany']}
}
第二场比赛(错误):
{
$and: [
{ level: { $ne: 'Begginer'} },
{ country: { $eq: 'United States' } },
]
}
我不想在第二个比赛阶段再次添加国家/地区数组。
答案 0 :(得分:-1)
您需要一个$or
,以便保留所有非“美国”的记录:
db.stuff.aggregate([
{ $match: {
country: {$in: ['United States', 'Germany'] }
}
},
{ $match: {
$or: [
{ country: { $ne: 'United States' } },
{ country: { $eq: 'United States' }, level: { $ne: 'Begginer'} }
]
}
}
]);
然后您可以将2个匹配项组合为一个。
db.stuff.aggregate([
{ $match: {
country: {$in: ['United States', 'Germany'] },
$or: [
{ country: { $ne: 'United States' } },
{ country: { $eq: 'United States' }, level: { $ne: 'Begginer'} }
]
}
}
]);
这两个查询都将输出:
{
"_id" : ObjectId("5e999bdee125b211df7f361a"),
"country" : "United States",
"personName" : "John",
"level" : "Average"
}
{
"_id" : ObjectId("5e999bdee125b211df7f361c"),
"country" : "Germany",
"personName" : "John",
"level" : "Average"
}