[英]MongoDB using regex to query array of strings and find the document
I have a collection of ORDERS which is like:我有一个订单集合,如下所示:
_id:5f8e7d8084378609b2dca93f
user_id:"5f8465a777b1814c588521e2"
price:96
city:"Mumbai City"
totalCost:96
_id:5f8e7d8084378609b2dca93f
user_id:"5f8465a777b1814c588521e2"
price:96
city:"Delhi"
totalCost:96
Then in my API I receive data which is in form of array:然后在我的 API 中,我接收到数组形式的数据:
driverCity = ['Mumbai', 'Ahmednagar', 'Yavatmal', 'Warud', 'Umred']
Now how do I query my ORDERS collection and then check that ORDER.city
is present as a substring is my driverCity
variable by regex ?现在我如何查询我的 ORDERS 集合,然后通过正则表达式检查
ORDER.city
是否存在作为我的driverCity
变量的子字符串? it means that if a substring like "mumbai" is present in ORDER.city
and also in this array I want that result.这意味着如果像“mumbai”这样的子字符串出现在
ORDER.city
和这个数组中,我想要那个结果。
If you're querying from the MongoDb driver for Nodejs then you can make a case-insentitive regex query:如果您从 MongoDb 驱动程序查询 Nodejs,那么您可以进行不区分大小写的正则表达式查询:
const driverCity = ['Mumbai', 'Ahmednagar', 'Yavatmal', 'Warud', 'Umred'];
db.collection("ORDERS").find({
city: new RegExp(driverCity.map(city => `(${city})`).join('|'),'i')
})
NOTE: Regex queries in mongodb (or anywhere, really) are a bit heavy and can be slow and resource-intensive.注意: mongodb(或任何地方,真的)中的正则表达式查询有点繁重,可能很慢且占用大量资源。 I would recommend your
city
key in the ORDERS collection is indexed.我建议您将 ORDERS 集合中的
city
键编入索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.