Home > Enterprise >  Find documents with $gte or $lte which has numbers as string values in arrays
Find documents with $gte or $lte which has numbers as string values in arrays

Time:02-20

I have a MongoDB collection that contains documents as follows:

{
 "_id": ObjectId(.....),
 "name": "John",
 "contacts": [
    {
      "name": "henry",
      "age": "22"
    },
    {
      "name": "merry",
      "age": "12"
    }
 ]
}

I want to find documents which have contacts.age is less than 20. I tried the following mongo query but had no luck. Anyone can help me out?

document.Users.find({'$expr':{'$lte': [{'$toInt':'$contacts.age'}, '20'] }})

Above query gives following error:

Query failed with error code 241 and error message 'Executor error during find command :: 
caused by :: 
Unsupported conversion from array to int in $convert with no one rror value' on server

CodePudding user response:

If you want all document (without change anything) you can try this aggregation query:

The trick here is to get only documents where there is one true in the array returned from condition "$lte": [{"$toInt": "$$this"},20].

That's mean that only will be matched documents which has an array with a value (minimum one subdocument) matched.

db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$in": [
          true,
          {
            "$map": {
              "input": "$contacts.age",
              "in": {
                "$lte": [{"$toInt": "$$this"},20]
              }
            }
          }
        ]
      }
    }
  }
])

Example here

Also if you want to filter the values in the array (and output only values where condition is matched) you can use $filter like this:

db.collection.aggregate([
  {
    "$addFields": {
      "contacts": {
        "$filter": {
          "input": "$contacts",
          "cond": { "$lte": [ { "$toInt": "$$this.age" }, 20 ] }
        }
      }
    }
  }
])

Example here

  • Related