Build this LEFT() “SQL” in MongoDB Query?

2019-08-06 13:48发布

Have an BsonDocument collection with PhoneNumber in the "1234567890" format. This SQL gets all the PhoneNumbers with the Area Codes between 300 and 399;

WHERE (LEFT(PhoneNumber,3) BETWEEN '300' AND '399') 

How would I do this in MongoDB? I would like to use the MongoDB.Driver.Builders if possible.

3条回答
2楼-- · 2019-08-06 14:09
{'PhoneNumber': /^3/ } or {'PhoneNumber': {'$regex': '^3'}}
查看更多
劫难
3楼-- · 2019-08-06 14:14

If you just want phone number that's starts from number '3' you can just use smart decision of @mstearn, here just c# realization:

var query = Query.EQ("PhoneNumber", new BsonRegularExpression("^3"));

But lets say if you need query first 3 numbers in range 345 -- 369 to make it work (without slow operators: $where, $regex) you can create additional field and store there first 3 numbers (area code) of phone. And then use query proposed by @yi_H , here again c# driver realization:

var query = Query.GTE("PhoneAreaCode", 345).LTE(369);

Don't care about extra field in mongodb -- it's common practice. Extra fields usual working faster than any calculation during querying.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-08-06 14:24
{'PhoneNumber': {'$gte': '300', '$lt': '400'}}
查看更多
登录 后发表回答