将$ lookup结果转换为对象而不是数组

时间:2017-01-11 23:45:57

标签: javascript arrays node.js mongodb mongoose

我正在从_id执行$ lookup。所以结果总是1个文件。因此,我希望结果是一个对象,而不是一个包含一个项目的数组。

let query = mongoose.model('Discipline').aggregate([
    {
      $match: {
        project: mongoose.Types.ObjectId(req.params.projectId)
      },
    },
    {
      $lookup: {
        from: "typecategories",
        localField: "typeCategory",
        foreignField: "_id",
        as: "typeCategory"
      }
    },
    {
      $project: {
        title: 1, typeCategory: "$typeCategory[0]"
      }
    }
  ]);

此表示法:"$typeCategory[0]"无效。有没有聪明的方法呢?

4 个答案:

答案 0 :(得分:17)

您可以使用$unwind。它从输入文档中解构数组字段,以输出每个元素的文档

let query = mongoose.model('Discipline').aggregate([
    {
      $match: {
        project: mongoose.Types.ObjectId(req.params.projectId)
      },
    },
    {
      $lookup: {
        from: "typecategories",
        localField: "typeCategory",
        foreignField: "_id",
        as: "typeCategory"
      }
    },
    {$unwind: '$typeCategory'},
    {
      $project: {
        title: 1, typeCategory: "$typeCategory"
      }
    }
  ]);

答案 1 :(得分:2)

我们需要在$unwind之后使用$lookup,例如以下查询。

db.device.aggregate([
  {
    $match: {
      deviceId: "000012345678901"
    }
  },
  {
    $lookup: {
      from: "customer",
      localField: "customerId",
      foreignField: "_id",
      as: "customers"
    }
  },
  {
    $lookup: {
      from: "asset",
      localField: "assetId",
      foreignField: "_id",
      as: "assets"
    }
  },
  {
    $unwind: "$customers"
  },
  {
    $unwind: "$assets"
  },
  {
    $project: {
      deviceId:1,
      customers: {
        customerId:"$customers._id",
        alert: "$customers.alert"
      },
      assets: {
        "assetId" : "$assets._id",
        "minSpeed" : "$assets.minSpeed",
        "maxSpeed" : "$assets.maxSpeed",
        "minTemperature" : "$assets.minTemperature",
        "maxTemperature" : "$assets.maxTemperature"
      }
    }
  }
]).pretty()

答案 2 :(得分:1)

您可以在$project阶段使用$arrayElemAt

$arrayElemAt的语法为{ $arrayElemAt: [ <array>, <idxexOfArray> ] }

像:

mongoose.model('Discipline').aggregate([
   {
      $match: {
        project: mongoose.Types.ObjectId(req.params.projectId)
      },
   },
   {
      $lookup: {
        from: "typecategories",
        localField: "typeCategory",
        foreignField: "_id",
        as: "typeCategory"
      }
   },
   {
      $project: {
         name: 1, typeCategory: {$arrayElemAt:["$typeCategory",0]}
      }
   }
]);

答案 3 :(得分:0)

用于合并两个集合:

{$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$typeCategory", 0 ] }, "$$ROOT" ] } }    }, 

{ $project: { typeCategory: 0 } }