Home > database >  How to conditionally find records from mongodb using node
How to conditionally find records from mongodb using node

Time:12-04

[ 
  {
   name: 'Some one'
   rep_id: '101',
   user_ids: ['102','103','104']
  },
  {
   name: 'Some one else'
   rep_id: '106',
   user_ids: ['102','103','104','105']
  },
]

I want to search records with rep_id from mongodb. If rep_id is not matched it should search the same id in user_ids array. If it's not present in user_ids array as well, it should skip that record. I'm able to find with rep_id being matched but how can I do the same if it's not matched and it's present in user_ids array. From the above records, if rep_id is 101 it should give me the first record and if rep_id is 102 it should give me the both the records since 102 is present in both user_ids array.

Even a hint of the solution will be enough

CodePudding user response:

use $or

db.collection.aggregate([
  {
    "$match": {
      "$or": [
        {
          rep_id: "102"
        },
        {
          user_ids: "102"
        }
      ]
    }
  }
])

mongoplayground

  • Related