Home > other >  MongoDB match with expr gt lt of a field with value in array of string
MongoDB match with expr gt lt of a field with value in array of string

Time:04-12

{
prediction:{
        B-experience:["5"]    
           }
       }

Here,I need to find the B-experience is greater than and less than by some min and max values.In my document B-experience is in array of string. So i have to convert that array string in to int and aggregate match by expr with "gt" and "lt". I have tried with so many methods. But not getting desired result. Can some could help me out.

CodePudding user response:

You can use $arrayElemAt to get the string out of the array, and $toInt in order to cast the string to int.

db.collection.aggregate([
  {
    $project: {
      predictionBexperience: {
        "$arrayElemAt": [
          "$prediction.B-experience",
          0
        ]
      }
    }
  },
  {
    $project: {
      predictionBexperience: {
        "$toInt": "$predictionBexperience"
      }
    }
  },
  {
    $match: {
      predictionBexperience: {
        $gt: 2,
        $lte: 7
      }
    }
  }
])

As can be seen on the playground with some more sample data.

  • Related