Mongo 如果在 $match 和 $or 中

Mongo if inside $match and $or

我已经坚持了很长一段时间。 我想根据表单中的两个输入过滤 specials.name 字段 - select 和输入字段。问题是,无论我尝试什么,它总是选择它。 有没有办法把 if, else 块放在 $or 里面让它工作?

这是我尝试的最后一件事,现在它始终在输入字段 searchInput 上运行,它不会对 select 菜单中的更改做出反应。

{
 $match: { 
  $or: [ 
   { 'specials.name':{$in :[searchSpecials, searchInput]}}, 
  ] 
 }
}

const searchSpecials = req.body.searchSpecials
const searchInput = req.body.search

如果两个输入是字符串,这会按预期工作:

db.collection.aggregate([
  {
    $match: {"specials.name": {$in: ["Malinda", "Joseph"]}}
  }
])

和returns:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "specials": {
      "name": "Malinda"
    }
  },
  {
    "_id": ObjectId("5a934e000102030405000002"),
    "specials": {
      "name": "Joseph"
    }
  }
]

如您所见here, on the playground。 不需要 $or,因为 $in 将 return 所有具有 specials.name 的文档都包含在选项列表中。