javascript - MongoDB:未知运算符:$ 或

标签 javascript mongodb

我正在尝试对 mongoDB 进行简单或查询,但确实收到错误 MongoError:未知运算符:$ 或

有人可以解释我做错了什么吗?

const query = {
  title: { $exists: true },
  category: { $exists: true, $ne: [] }
}

// ...do some stuff
// now need to change category query...

query.category = {
  $or: [
    { $exists: false },
    { $eq: [] }
  ]
}

// should return documents with missing category field or empty array value
Content.find(query)

最佳答案

简短的回答是 $or语句不适用于单个字段,而是必须为每个项目指定字段:

$or: [
  {category: {$exists: false}},
  {category: {$eq: []}}
]
解释
根据 the manual , $or语法如下:
{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

请注意,与许多运算符不同,它不包含字段名称。例如,对比 $exists ,其中确实包括字段名称:
{ field: { $exists: <boolean> } }

换句话说,而不是:
{
  title: { $exists: true },
  category: {
    $or: [
      {$exists: false},
      {$eq: []}
    ]
  }
}
你需要:
{
  title: { $exists: true },
  $or: [
    {category: {$exists: false}},
    {category: {$eq: []}}
  ]
}
问题的例子
将所有这些与您的确切示例放在一起,您最终会得到:
const query = {
  title: { $exists: true },
  category: { $exists: true, $ne: [] }
}

// ...do some stuff
// now need to change category query...

delete query.category
query.$or = [
  {category: {$exists: false}},
  {category: {$eq: []}}
]

// should return documents with missing category field or empty array value
Content.find(query)

关于javascript - MongoDB:未知运算符:$ 或,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48530123/

相关文章:

mongodb - 让记录器在 Doctrine MongoDB ODM 中工作?

蒙戈数据库 4.2.8 : Unable to add session into the cache because the number of active sessions is too high

javascript - 如何获取选择选项的值,并使用它来查询数组,以填充另一个输入

javascript - 组合组件上的 onBlur 事件(输入 + 按钮)

javascript - 在多个边界中搜索 map 坐标

javascript - 在不同域上动态加载样式表在 Firefox 中不起作用

javascript - 如何在 JavaScript 中实现由时钟解析的 monad Promise?

javascript - 使用 Firefox 的 Downloads.jsm 在观察文件的同时一次下载一个文件?

mongodb - mongodb中大对象保存多文档好还是少文档好?

linux - Docker Compose 中的 MongoDb - 提供配置