0

my documents in mongodb collection :

{ 
  'id' : 'ID1',
  'status' : 'ST1',
  'logs' : [
    {
      'id' : 'ID2',
      'status_old' : 'ST2',
      'status_new' : 'ST3',
    },
    {
      'id' : 'ID3',
      'status_old' : 'ST3',
      'status_new' : 'ST4',
    }
  ]
},
{ 
  'id' : 'ID4',
  'status' : 'ST4',
  'logs' : [
    {
      'id' : 'ID5',
      'status_old' : 'ST2',
      'status_new' : 'ST3',
    }
  ]
}

I want to pass the documents through the following two filters

filter1 : 
where
   ( status    = 'ST1'  OR
    status_old = 'ST1'  OR
    status_new = 'ST1'  )

Then the answer obtained should be placed in the following filter (condition):

filter2 : 
where
   ( status    = 'ST2'  OR
    status_old = 'ST2'  OR
    status_new = 'ST2'  )

The answer is stated with two conditions and according to the documents provided above, the following is the case:

{ 
  'id' : 'ID1',
  'status' : 'ST1',
  'logs' : [
    {
      'id' : 'ID2',
      'status_old' : 'ST2',
      'status_new' : 'ST3',
    },
    {
      'id' : 'ID3',
      'status_old' : 'ST3',
      'status_new' : 'ST4',
    }
  ]
},
3
  • logs is an array right? So would the filters match any item in the array ? Commented Feb 26, 2022 at 15:51
  • yes . logs is array , I edited the question Commented Feb 26, 2022 at 15:53
  • yes , filters match any item in the array AND status field Commented Feb 26, 2022 at 16:10

1 Answer 1

1

since you are not filtering out any elements from the logs array this looks like an aggregation with 2 $match stages with $or in it

db.collection.aggregate([
  {
    $match: {
      $or: [
        {
          "status": "ST1"
        },
        {
          "logs.status_old": "ST1"
        },
        {
          "logs.status_new": "ST1"
        }
      ]
    }
  },
  {
    $match: {
      $or: [
        {
          "status": "ST2"
        },
        {
          "logs.status_old": "ST2"
        },
        {
          "logs.status_new": "ST2"
        }
      ]
    }
  }
])

demo

Sign up to request clarification or add additional context in comments.

2 Comments

We also have other filters so that it is not crowded and complicated, it is not mentioned in the question, does this method work properly with other filters?
can you do some checks with some sample data in mongoplayground.net/p/VYpzgAUl6qa

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.