My targred is to exclude records which are already mateched from previous match aggregation in MongoDb.
In first match I need to fetch records from two countries: United States and Germany.
In second match I need to exclude records from given country, for example United States AND level of "Begginer", but keep other records from United States and Germany. How is that possible? Example Data:
[
{
country: 'United States',
personName: 'John',
level: 'Average',
},
{
country: 'United States',
personName: 'Rina',
level: 'Begginer',
},
{
country: 'Germany',
personName: 'John',
level: 'Average',
}
]
First match (correct):
{
country: {$in: ['United States', 'Germany']}
}
Second match (wrong):
{
$and: [
{ level: { $ne: 'Begginer'} },
{ country: { $eq: 'United States' } },
]
}
I do not want to add countries array again in second match phase.
You'll need an $or
so that you keep all records that are not 'United States':
db.stuff.aggregate([
{ $match: {
country: {$in: ['United States', 'Germany'] }
}
},
{ $match: {
$or: [
{ country: { $ne: 'United States' } },
{ country: { $eq: 'United States' }, level: { $ne: 'Begginer'} }
]
}
}
]);
You can then just combined the 2 matches in to one.
db.stuff.aggregate([
{ $match: {
country: {$in: ['United States', 'Germany'] },
$or: [
{ country: { $ne: 'United States' } },
{ country: { $eq: 'United States' }, level: { $ne: 'Begginer'} }
]
}
}
]);
Both these queries will output:
{
"_id" : ObjectId("5e999bdee125b211df7f361a"),
"country" : "United States",
"personName" : "John",
"level" : "Average"
}
{
"_id" : ObjectId("5e999bdee125b211df7f361c"),
"country" : "Germany",
"personName" : "John",
"level" : "Average"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.