【问题标题】:aggregation in nodejs resulting in nested json, can I get it without nesting, taking only one data _id from all collectionsnodejs中的聚合导致嵌套的json,我可以在没有嵌套的情况下获取它,只从所有集合中获取一个数据_id
【发布时间】:2020-04-28 19:58:55
【问题描述】:

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

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' 
  }
]

【问题讨论】:

    标签: arrays node.js mongodb collections aggregation-framework


    【解决方案1】:

    您可以使用$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] },
        },
      }
    ]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      • 2012-03-05
      • 2017-08-11
      • 2011-07-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      相关资源
      最近更新 更多