Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB如何查找未定义$lookup的文档(聚合)_Mongodb_Nosql_Aggregate - Fatal编程技术网

MongoDB如何查找未定义$lookup的文档(聚合)

MongoDB如何查找未定义$lookup的文档(聚合),mongodb,nosql,aggregate,Mongodb,Nosql,Aggregate,我在origin集合中有一个文档,其中包含或不包含对外国集合文档的引用-密钥不是强制性的,因此有时会丢失 在这种情况下,$lookup“失败”,并且所需的文档无法从数据库中获取 这是管道: { $lookup: { from: "tables", let: { "enginefuel_type": "$engine.fuel_type" }, pipeline: [ { $match: { $expr: { $eq: ["$_id",

我在origin集合中有一个文档,其中包含或不包含对外国集合文档的引用-密钥不是强制性的,因此有时会丢失

在这种情况下,$lookup“失败”,并且所需的文档无法从数据库中获取

这是管道:

{
    $lookup: {
      from: "tables",
      let: { "enginefuel_type": "$engine.fuel_type" },
      pipeline: [
        { $match: { $expr: { $eq: ["$_id", "$$enginefuel_type"] }}},
        { $project: { title: 1 }}
      ],
      as: "engine.fuel_type"
    }
  },
  {
    $unwind: "$engine.fuel_type"
  },

  {
    $lookup: {
      from: "tables",
      let: { "enginegear": "$engine.gear" },
      pipeline: [
        { $match: { $expr: { $eq: ["$_id", "$$enginegear"] }}},
        { $project: { title: 1 }}
      ],
      as: "engine.gear"
    }
  },
  {
    $unwind: "$engine.gear"
  }
无论如何,我都需要找到该文档-无论它是否有引擎.fuel\u type和/或引擎.gear字段。 如果有,那么它应该从外文获取文档,否则只保留空文档而不忽略整个文档

在进行聚合查询之前,我考虑使用一些预if语句检查字段是否存在(也可以更有效,减少对数据库的请求)


有什么好方法可以做到这一点吗?

查找阶段按您的需要工作,即使该字段不在源集合中,文档也不会被忽略,并且将成为包含0个元素的“engine.fuel_type”数组结果的一部分

它是一个展开阶段,用于删除具有0个数组元素的文档。幸运的是,stage提供了preserveNullandmptyarray:选项,其中包括所有结果。 所以你可以试着这样做:-

$lookup: {
      from: "tables",
      let: { "enginefuel_type": "$engine.fuel_type" },
      pipeline: [
        { $match: { $expr: { $eq: ["$_id", "$$enginefuel_type"] }}},
        { $project: { title: 1 }}
      ],
      as: "engine.fuel_type"
    }
  },
  {
    $unwind: {
      path: "engine.fuel_type",
      preserveNullAndEmptyArrays: true
    }
  }

Lookup stage根据需要工作,即使该字段不在源集合中,文档也不会被忽略,并且将成为包含0个元素的“engine.fuel_type”数组结果的一部分

它是一个展开阶段,用于删除具有0个数组元素的文档。幸运的是,stage提供了preserveNullandmptyarray:选项,其中包括所有结果。 所以你可以试着这样做:-

$lookup: {
      from: "tables",
      let: { "enginefuel_type": "$engine.fuel_type" },
      pipeline: [
        { $match: { $expr: { $eq: ["$_id", "$$enginefuel_type"] }}},
        { $project: { title: 1 }}
      ],
      as: "engine.fuel_type"
    }
  },
  {
    $unwind: {
      path: "engine.fuel_type",
      preserveNullAndEmptyArrays: true
    }
  }