mongodb find element in nested array

Viewed 43

I need to create aggregator with condition where any of the element in dat is less then -85 it first display the list of ArrObj with date and time.

I tied with following aggregator statement but unable to get the results .

{
  'ArrObj.dat':{
    $filter:{
      input:'$ArrObj.dat',
      as:"res",
      cond:{
             $gt:["$$res",-80],
      }
      
    }
  }
}

Database structure

    "ArryObj": [{
    "dat": [-84.2, -83.9, -84.9, -85.3, -86.8, -85.6, -84.6, -86.4],
    "Date": "26-05-2021",
    "Time": "13:02:42",
    },{
    "dat": [-90.2, -83.9, -84.9, -85.3, -86.0, -85.0, -84.2, -86.4],
    "Date": "26-05-2021",
    "Time": "13:02:42",
    }]

Required Result

        "ArryObj": [{
        "dat": [-90.2, -83.9, -84.9, -85.3, -86.0, -85.0, -84.2, -86.4],
        "Date": "26-05-2021",
        "Time": "13:02:42",
        }]
1 Answers

You need $map and $filter

  • $map to loop through all objects
  • $filter to filter y condition while looping

Here is the code

db.collection.aggregate([
  {
    $project: {
      "ArryObj": {
        "$map": {
          "input": "$ArryObj",
          "as": "arr",
          "in": {
            "dat": {
              "$filter": {
                "input": "$$arr.dat",
                "as": "d",
                "cond": {
                  $gt: [ "$$d", -85 ]
                }
              }
            }
          }
        }
      }
    }
  }
])

Working Mongo playground

Related