MongoDB-在查询中处理$in中不存在的数组

MongoDB-在查询中处理$in中不存在的数组,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我有以下疑问: db.getCollection('authors').aggregate([ { $match: {} }, { $sort: { name: -1 } }, { $addFields: { x_id___as___string: { $toString: "$_id" } } }, { $lookup: { from: "books", let: { fkField:"$x_id___as___string" }, p

我有以下疑问:

db.getCollection('authors').aggregate([
  { $match: {} }, 
  { $sort: { name: -1 } }, 
  { $addFields: { x_id___as___string: { $toString: "$_id" } } }, 
  { $lookup: {
      from: "books",
      let: { fkField:"$x_id___as___string" },
      pipeline: [{ $match: { $expr: { $in: ["$$fkField", "$authorIds"] } } }],
      as: "books"
    } 
  }
])
这很好,除非
authoritds
数组在一些连接的文档中丢失,在这种情况下,我得到的错误是

“errmsg”:“$in需要一个数组作为第二个参数,发现:缺少”, “代码”:40081, “代号”:“位置40081” }:聚合失败

我已经确认,手动将
authorIds
作为空数组添加到缺少它的文档中可以修复查询。我的问题是:

如何调整此查询以使用不存在的
authorIds
字段?


我是否应该将我的
$expr
更改为
$and
查询,第一个值是检查数组是否存在?Mongo是否保证短路?在查询中,我是否可以添加一个更简单的检查

在查找管道$expr中添加$cond

db.getCollection('authors').aggregate([
  { $match: {} }, 
  { $sort: { name: -1 } }, 
  { $addFields: { x_id___as___string: { $toString: "$_id" } } }, 
  { $lookup: {
      from: "books",
      let: { fkField:"$x_id___as___string" },
      pipeline: [{ $match: { $expr: { $in: ["$$fkField", {$cond: {if: {$gt: ["$authorIds", null]}, then: "$authorIds", else: []}}] } } }],
      as: "books"
    } 
  }
])
这将检查是否存在
authorIds
。要确保它是一个实际数组,可以使用
$isArray

db.getCollection('authors').aggregate([
  { $match: {} }, 
  { $sort: { name: -1 } }, 
  { $addFields: { x_id___as___string: { $toString: "$_id" } } }, 
  { $lookup: {
      from: "books",
      let: { fkField:"$x_id___as___string" },
      pipeline: [{ 
        $match: { 
          $expr: { 
            $in: [
              "$$fkField", 
              { $cond: { if: { $isArray: "$authorIds" }, then: "$authorIds", else: [] } }
            ] 
          } 
        } 
      }],
      as: "books"
    } 
  }
])

是 啊但是,
isArray
不是更好吗,即
{$cond:{如果:{$isArray:$authorIds},那么:“$authorIds”,else:[]}
?我把它编辑成你的答案,你同意吗?我把它作为第二个例子加进去了,希望你不介意。非常感谢!为什么管道中需要
{$match:{},
阶段?@prasad_uu在这个特定示例中没有做任何事情,你是对的