MongoDB:无法解析 $convert 中的 objectId '',没有 onError 值:解析为 OID 的字符串长度无效,预期为 24,但发现为 0

Ste*_*ero 3 aggregate mongodb

我正在创建一个聚合查询,但我遇到了一些需要转换为 ObjectID 的字段的问题。某些文档在字段(null,'')中没有任何内容,因此我想忽略这些情况。

{
   "$project": {
    "Company": {
        "$toObjectId": "$Company"
    },
    "Lease": {
        "$toObjectId": "$Lease"
    },
    "Well": {
        "$toObjectId": "$Well"
   }
}
Run Code Online (Sandbox Code Playgroud)

我试过类似的东西:

{$ifNull: [{ $toObjectId: "$Company" }, ''] }
Run Code Online (Sandbox Code Playgroud)

但我仍然收到错误。

解决此问题的最佳方法是什么?

Ste*_*ero 6

我意识到我使用的是$toObjectId的简短语法,它没有 onNull 或 onError 选项。

我需要恢复到 $convert:

{$convert: {input: '$Company', to : 'objectId', onError: '',onNull: ''}}
Run Code Online (Sandbox Code Playgroud)

来源