【问题标题】:Mongodb check if any string from array of strings is present another stringMongodb检查字符串数组中的任何字符串是否存在另一个字符串
【发布时间】:2020-10-20 17:21:22
【问题描述】:

大家好,我有两个“ORDERS”和“DRIVERS”系列

ORDER 集合就像

_id:5f8e7d8084378609b2dca93f
user_id:"5f8465a777b1814c588521e2"
price:96
city:"Mumbai City"
totalCost:96

所以这里的城市来自谷歌地图,这意味着我只需在我的谷歌地图中拖动标记,它将城市设置为“孟买市”

DRIVER 集合就像

_id:5f84485b0933073435cdee30
name:"Ratnabh Kumar Rai"
password:"$2b$10$MSxPYKkdn7HbpjoYCgbg1.RewN5Q26CFxSVLrFqR6e.J4jSNd7G5."
city:[ 'Mumbai', 'Ahmednagar', 'Yavatmal', 'Warud', 'Umred' ]
status:1

城市由管理员手动分配

我想要的是过滤掉我的 ORDERS 集合中的 city 是否在 DRIVERS 集合中......直到现在我正在做的是

let driverCity = data.city; /////city is the driver city which i am sending from front-end/////

所以现在 driverCity=[ 'Mumbai', 'Ahmednagar', 'Yavatmal', 'Warud', 'Umred' ] 和订单城市仍然是“孟买市”

let doc = await db
        .collection("orders")
        .find({
          $and: [
            { city: { $in: driverCity } },
          ],
        })
        .toArray();

但它会检查确切的元素,所以如果谷歌设置“孟买”而不是“孟买市”,这将是完美的,但现在我有“孟买市”我应该怎么做?

无论如何,我可以检查 driverCity 数组中的任何字符串是否以 order city 或任何其他方式存在?

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    您可以使用RegExp(正则表达式)来匹配 Mongo 中的部分数据。

    let doc = await db
    .collection("orders")
    .find({
      $and: [
        { city: new RegExp(driverCity,'i') },  // 'i' is for ignore case
      ],
    })
    .toArray();
    

    如果您想更好地控制搜索内容,您还可以使用正则表达式通配符和控制字符:

    new RegExp(`^${driverCity}`,'i') // search cities starting with "Mumbai"
    

    或者甚至在您的搜索中添加一个可选的City 字符串:

    new RegExp(`^${driverCity}(\\s+City)$`,'i') // search either Mumbai or Mumbai City
    

    无论如何,正则表达式搜索速度要慢得多,并且可能导致不精确的结果,因此请考虑修改来自 Google 的数据,然后再将其插入orders 集合,以便稍后匹配您的驱动程序搜索。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-11
      • 2011-03-24
      • 1970-01-01
      • 2022-12-14
      • 2011-02-07
      • 2013-05-12
      • 1970-01-01
      相关资源
      最近更新 更多