首页 > 解决方案 > Mongo 错误 - 无法规范化查询:BadValue 不支持的投影选项

问题描述

我是 MongoDB 新手,正在尝试执行查询。我有一个公司集合和公司 ID 数组。我想得到attributes.0.ccode存在attributes.0.ccode且不为空的结果,并将在 array( cdata)中提供的 id 中进行检查

var query = Company.find({ _id: { $in: cdata } },{ "attributes.0.ccode": { $exists: true }, $and: [ { "attributes.0.ccode": { $ne: "" } } ] }).select({"attributes": 1}).sort({});

我得到的错误是

"$err": "Can't canonicalize query: BadValue Unsupported projection option: attributes.0.ccode: { $exists: true }",
"code": 17287

我认为这是一个括号问题,但无法弄清楚在哪里。

非常感谢任何帮助。

标签: arraysmongodbmongodb-query

解决方案


在您的代码{ _id: { $in: cdata } }中被解释为查询,以及其他所有内容,从,{ "attributes.0.ccode": { $e..Projection(要显示的字段)开始。尝试重构您的代码,以便_id: {$in ...}查询的其余部分属于同一个更高级别的对象。像这样的东西:

var query = Company.find({
  _id: {
    $in: cdata
  },
  "attributes.0.ccode": {
    $exists: true
  },
  $and: [
    {
      "attributes.0.ccode": {
        $ne: ""
      }
    }
  ]
}).select({"attributes": 1}).sort({});

推荐阅读