简体   繁体   中英

MongoDB match with expr+gt+lt of a field with value in array of string

{
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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM