Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Find by string length

I have a collection containing field "MobileNumber". I need to find records with following conditions:

1- start with 9613 and number of characters different than 10
2- start with 961 and not 9613 and number of characters different than 11

Collection looks like this:

[
 {"_id": ObjectId("..."), "MobileNumber": "961xxxx", "Name" : "John"},
 {"_id": ObjectId("..."), "MobileNumber": "961xxxx", "Name" : "Alex"},
 {"_id": ObjectId("..."), "MobileNumber": "971xxxx", "Name" : "Fatima"},
 {"_id": ObjectId("..."), "MobileNumber": "971xxxx", "Name" : "Mughees"},
 {"_id": ObjectId("..."), "MobileNumber": "901xxxx", "Name" : "Mike"},
 {"_id": ObjectId("..."), "MobileNumber": "911xxxx", "Name" : "Thomas"}
]

I tried like this:

db.mobileinfos.find(
{ 
   $expr: { 
        $and:[ 
             {MobileNumber: /^961/},
             {$ne: [{ $strLenCP: "$MobileNumber" }, 10 ] }
           ]    
} 
}
)

But it looks like above query ignored first condition of $and and gave records for only second condition.

I am getting all mobile numbers whose length not equal to 10. But i need only those mobile numbers start with 961 and length is not equal to 10. Kindly advice.

like image 772
Malik Awan Avatar asked Mar 08 '26 01:03

Malik Awan


1 Answers

MongoPlayground

But i need only those mobile numbers start with 961 and length is not equal to 10.

Here it is:

db.collection.find({
  MobileNumber: {
    $regex: "^961"
  },
  "$expr": {
    "$ne": [
      {
        "$strLenCP": "$MobileNumber"
      },
      10
    ]
  }
})
like image 87
Anton Avatar answered Mar 10 '26 00:03

Anton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!