Home > database >  MongoDB aggregation, nodejs generate dynamic query with AND & OR
MongoDB aggregation, nodejs generate dynamic query with AND & OR

Time:01-17

I have query with aggregation for MongoDB in my nodejs code.

const query = {
  '$expr':{
    '$and':[
      {'$eq': ['$appId', req.user.appId]},
    ]
  }
}

from the frontend comes filter object

{
  shops: '604c776763c302032e610347',
  offset: '0',
  limit: '20',
}

I need dynamically push shops id in my query. need to be appId -> user.appID AND targetFrom || targetTo <- shops(from the filter object)

shops can be one id or array of ids, for this I'm using $in operator

query['$expr']['$and'].push({
  $eq: [
    {
      $or: [
        {"targetFrom": {$in: bb}},
        {"targetTo": {$in: bb}}
      ]
    }
  ]
})

the old version of code was:

const query = {
  $and: [
    {appId: req.user.appId}
  ]
}

query['$and'].push({
  $or: [
    {"targetFrom": {$in: bb}}, <- in bb is mongodb objectID
    {"targetTo": {$in: bb}}
  ]
})

CodePudding user response:

Please see if the following addresses your requirement:

Mongoplayground link

Assumptions:

  1. req.user.appId is a string.
  2. bb is an array of either objectIds or strings ([ObjectId("asdfsd"),ObjectId("badsfds")], etc.)
const query = {
  "$expr": {
      $and: [{
        "appId": req.user.appId,
      }]
      
  }
}

query['$expr']['$and'].push({
  $or: [
    {
      $in: [
        "$targetFrom",
        bb
      ]
    },
    {
      $in: [
        "$targetTo",
        bb
      ]
    }
  ]
})
  •  Tags:  
  • Related