【问题标题】:Mongoose.Find() with arrays and OR-operatorsMongoose.Find() 与数组和 OR 运算符
【发布时间】:2019-02-28 17:32:36
【问题描述】:

我正在尝试搜索与 json 对象匹配的数据库行。

例子:

var searchParams = {
    city: ['New York City', 'Budapest'], 
    jobs: ['Assistent'] //Can be multiple 
}

//If "city" is equal to one of the searchParams.city variables
//AND jobs is equal to one of the searchParams.jobs variables

var searchQuery = {
    $and: [
        {$or: clean_city},
        {$or: clean_cat}
    ]
}

Jobs.find(searchQuery, function(err, list){
    console.log(list);
});

我已经尝试了所有可以在 google 上找到的选项,但似乎没有任何方法适用于数组。

如果有人能提供帮助,我将非常感激。

问候

【问题讨论】:

  • 你的 db 对象是什么样的?

标签: javascript node.js mongodb mongoose mongodb-query


【解决方案1】:

您可以找到一个示例 here,根据您的上下文,假设:

  • 使用searchParams,因为我不知道clean_* 变量中有什么
  • DB 字段为cityjob
{
  $and: [
    { $or: searchParams.city.map(city => ({ city })) },
    { $or: searchParams.jobs.map(job => ({ job })) }
  ]
}

哪个是更短的语法(如果数据库字段名称不同,您不能快捷方式):

{
  $and: [
    { $or: searchParams.city.map((city) => { return { city: city }; }) },
    { $or: searchParams.city.map((job) => { return { job: job }; }) }
  ]
}

【讨论】:

    【解决方案2】:

    假设您在 mongo db 中的对象如下所示:

    {
       "city": "New York City",
       "job": "Assistent"
    }
    

    你可以这样查询:

    Jobs.find({
       $and: [
          {
             city: { $in: ["NYC", "Paris"] }
          }, {
             job: { $in: ["Assistent"] }
          }
       ]
    })
    

    这将返回在 city 数组中包含 city 并且在 jobs 数组中包含 job 的任何对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多