How do we use override information in Mongo Query

How do we use override information in Mongo Query.
For example, we have 2 fields(Salary and Salary_override). If the user provide override information in Salary_override field, we need to consider this field as first priority. Suppose if this override field value is null or empty then we need to use salary field, not override field.
We should construct the mongo query dynamically. Please suggest how do we construct the Mongo query for this scenario.

Hi @Mansur_Ali ,

the following aggregation should work:

[{
 $project: {
  Salary: {
   $ifNull: [
    '$Salary_overide',
    '$Salary'
   ]
  }
 }
}]
db.test12.find()
{ _id: ObjectId("630cb9db2786520682ce36e5"),
  salary: 100,
  salary_overide: 'xxx' }
{ _id: ObjectId("6310876b46087690603641b0"), salary: 100 }
db.test12.aggregate([{
 $project: {
  salary: {
   $ifNull: [
    '$salary_overide',
    '$salary'
   ]
  }
 }
}])
{ _id: ObjectId("630cb9db2786520682ce36e5"), salary: 'xxx' }
{ _id: ObjectId("6310876b46087690603641b0"), salary: 100 }

Ty

1 Like

If mongoose is being used,
then it could be done by using init post hook.
It’s executed on each doc, loaded by a find query.

 schema.post('init', function() {
   if(this.Salary_override){
    this.Salary = this.Salary_override;
   }
  });