Reputation: 775
I have a set of conditions which I'm passing in $match
stage but for some reason i'd want to fetch data with another set of conditions. These conditions should have to be used in 'OR' conjunction.
i.e: $match(condition set1) || $match(condition set2)
Condition set 1:
$match: {
status: 'running',
hero: { $in: ['superman', 'batman', 'ironman'] },
playReport: null,
}
OR
Condition set 2:
Match condition, where `lastPlayed` time should be greater than the `playReport.timestamp`
Sample Data:
{
status: 'running',
hero: 'superman',
playReport: null
},
{
status: 'stopped',
hero: 'batman',
playReport: null
},
{
status: 'stopped',
hero: 'spiderman',
playReport: null
},
{
status: 'running',
hero: 'ironman',
playReport: {
timestamp: '2020-10-21T10:05:03.940+00:00'
}
lastPlayed: '2021-10-21T10:05:03.940+00:00'
},
{
status: 'running',
hero: 'batwoman',
playReport: null
},
{
status: 'stopped',
hero: 'thor',
playReport: null
}
Output:
{
status: 'running',
hero: 'superman',
playReport: null
},
{
status: 'running',
hero: 'ironman',
playReport: {
timestamp: '2020-10-21T10:05:03.940+00:00'
}
lastPlayed: '2021-10-21T10:05:03.940+00:00'
},
Upvotes: 1
Views: 147
Reputation: 36094
$or
operator to specify both conditions$expr
expression condition with $gt
operatordb.collection.aggregate([
{
$match: {
$or: [
{
status: "running",
hero: {
$in: ["superman", "batman", "ironman"]
},
playReport: null
},
{
$expr: {
$gt: [
"$lastPlayed",
"$playReport.timestamp"
]
}
}
]
}
}
])
Upvotes: 2