Ashish Bairwa
Ashish Bairwa

Reputation: 775

Using two different set of conditions to match and fetch data from db with aggregation pipeline

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

Answers (1)

turivishal
turivishal

Reputation: 36094

  • Use $or operator to specify both conditions
  • to match internal fields use $expr expression condition with $gt operator
db.collection.aggregate([
  {
    $match: {
      $or: [
        {
          status: "running",
          hero: {
            $in: ["superman", "batman", "ironman"]
          },
          playReport: null
        },
        {
          $expr: {
            $gt: [
              "$lastPlayed",
              "$playReport.timestamp"
            ]
          }
        }
      ]
    }
  }
])

Playground

Upvotes: 2

Related Questions