繁体   English   中英

nodejs中的聚合导致嵌套的json,我可以在没有嵌套的情况下得到它,只从所有collections中获取一个数据_id

[英]aggregation in nodejs resulting in nested json, can I get it without nesting, taking only one data _id from all collections

nodejs中的聚合导致嵌套的json,我可以在没有嵌套的情况下得到它,只从所有collections中获取一个数据_id。 是否有可能在没有嵌套 json 的情况下获取数据我正在尝试使用以下代码在 nodejs 中进行聚合。 我得到了下面 output session 中给出的 output。 但我想按预期获得 output output,因为我不能在循环中使用循环

Student.aggregate([
  {
    $match: { name: 'abcd'}
  },
  {
    $lookup:{
       from:'teachers',
       pipeline: [
        { 
          $match: { name: 'pqrs' } 
        },
        {
          $project:{
            "_id":1
          }
        }
       ],
       as: "teacherLookup"
    }
  },
  {
    $lookup:
     {
       from:'subjects',
       pipeline: [
        { 
          $match: { name: 'computer' } 
        },
        {
          $project:{
            "_id":1
          }
        }
 ],
       as: "subjectLookup"
     }
  }
])


output
[
  {
    _id: '52301c7878965455d2a4',
    teacherLookup: [ '5ea737412589688930' ],
    subjectLookup: [ '5ea745821369999917' ]
  }
]
I am expecting the output as (without nested json)
[
  {
    studentId: '5ea1c7878965455d2a4',
    teacherId: '5ea737412589688930' ,
    subjectId:  '5ea745821369999917' 
  }
]

您可以使用$arrayElemAt从数组中获取第一个元素。

Student.aggregate([
  {
    $match: { name: "abcd" },
  },
  {
    $lookup: {
      from: "teachers",
      pipeline: [
        {
          $match: { name: "pqrs" },
        },
        {
          $project: {
            _id: 1,
          },
        },
      ],
      as: "teacherId",
    },
  },
  {
    $lookup: {
      from: "subjects",
      pipeline: [
        {
          $match: { name: "computer" },
        },
        {
          $project: {
            _id: 1,
          },
        },
      ],
      as: "subjectId",
    },
  },
  {
    $project: {
      teacherId: { $arrayElemAt: ["$teacherId", 0] },
      subjectId: { $arrayElemAt: ["subjectId", 0] },
    },
  }
]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM