【问题标题】:Nodejs mongoose : how to retreive data from db collection related to other collectionNode Js mongoose:如何从与其他集合相关的数据库集合中检索数据
【发布时间】:2020-11-18 19:23:11
【问题描述】:

我想实现一个函数来处理学生、课程和教师数据(从 MongoDB 集合中加载),以便生成有关注册课程的学生的信息(并将其存储在另一个 MongoDB 集合中)。该函数报告每个学生的:

primary key
their name
the number of courses they are enrolled in

我想将此例程的输出存储在一个名为 coursereport 的 MongoDB 集合中,如下所示:

[
  {
    "_id": "jeff",
    "value": {
      "name": "Jeff Holland",
      "numbercourses": 2
    }
  },
  {
    "_id": "john.shore",
    "value": {
      "name": "John Shore",
      "numbercourses": 2
    }
  },
  {
    "_id": "lee2331",
    "value": {
      "name": "Lee Aldwell",
      "numbercourses": 1
    }
  },
  {
    "_id": "rcotter",
    "value": {
      "name": "Ray Cotter",
      "numbercourses": 2
    }
  },
  {
    "_id": "scott",
    "value": {
      "name": "Scott Mills",
      "numbercourses": 3
    }
  }
]

我的数据:

{
  "students": [
    {
      "_id": "john.shore",
      "name": {"first": "John", "last": "Shore"},
      "email": "john.shore@gmail.com",
      "major": "Electrical Engineering"
    },
    {
      "_id": "jeff",
      "name": {"first": "Jeff", "last": "Holland"},
      "email": "jeff@yahoo.com",
      "major": "Business"
    },
    {
      "_id": "scott",
      "name": {"first": "Scott", "last": "Mills"},
      "email": "scott@hotmail.com",
      "major": "Humanities/Art"
    },
    {
      "_id": "rcotter",
      "name": {"first": "Ray", "last": "Cotter"},
      "email": "rcotter@msn.com",
      "major": "Computer Science"
    },
    {
      "_id": "lee2331",
      "name": {"first": "Lee", "last": "Aldwell"},
      "email": "lee2331@aol.com",
      "major": "Graphic Design"
    }
  ],
  "courses": [
    {
      "_id": "HIST-1010",
      "name": "History of the World 1010",
      "description": "A bunch of really interesting things that actually happened",
      "students": ["scott", "john.shore"],
      "ratings": [3, 5, 4, 5, 4, 4, 2, 4]
    },
    {
      "_id": "ENGCOMP-1010",
      "name": "English Composition 1010",
      "description": "If you can't write well, you've got nothing!",
      "students": ["scott", "lee2331", "rcotter", "john.shore", "jeff"],
      "ratings": [4, 4, 5, 4, 5, 1, 5]
    },
    {
      "_id": "ART-1050",
      "name": "Artistic Interpretation 1050",
      "description": "Discover your inner beholder",
      "students": ["rcotter", "scott", "jeff"],
      "ratings": [3, 4, 3, 4, 4, 3, 4, 4]
    }
  ],   
  "instructors": [
    {
      "_id": "wally.r.binns",
      "name": {"first": "Wally", "middle": "r", "last": "Binns"},
      "email": "wally.r.binns@ssu.edu",
      "bio": "I was born in the middle of my mother's doctoral dissertation on Faraday Cage isolation. I've been an academic ever since...",
      "publications": [{
        "title": "Inverted Celestial Poetry",
        "source": "http://www.pubcentral.com/poetry/inverted-celestial-poetry"
      }],
      "courses": ["ENGLIT-2500"]
    },
    {
      "_id": "gerald.waterford.iii",
      "name": {"first": "Gerald", "last": "Waterford", "suffix": "III"},
      "email": "gerald.waterford.iii@ssu.edu",
      "bio": "My father's father was a great man. My father, not so much. I am restoring the family honor.",
      "publications": [{
        "title": "Grow, grow, little Dandelion",
        "source": "http://www.hopefulstories.com/my-dandelion"
      }, {"title": "The teapot and the spoon", "source": "http://www.dishsoap.com/teapot-spoon"}],
      "courses": ["ENGCOMP-1010", "HIST-1010"]
    },
    {
      "_id": "kim.b",
      "name": {"prefix": "Mrs.", "first": "Kim", "last": "Binnley"},
      "email": "kim.b@ssu.edu",
      "bio": "My mother told me 'Don't let those dopes push you around'. My life has been a constant struggle against dopeness ever since. Sigh...",
      "publications": [],
      "courses": ["ART-1050"]
    }
  ]
}

我从那个开始:

async function produceReport(db, callback) {
  const students = db.collection('students');
  const courses = db.collection('courses');
  const instructors = db.collection('instructors');

  // implement missing code that will create 'coursereport' mongo collection with student courses data

  callback();
}

module.exports = produceReport;

谁能帮帮忙

【问题讨论】:

    标签: node.js mongodb collections relation


    【解决方案1】:

    你必须使用$lookup

    定义为:

    要在输入文档中的字段与“已加入”集合的文档中的字段之间执行相等匹配,

    所以你必须加入studentscourses 以及后来的输出值instructors..

    看看这个查询:

    db.students.aggregate([
      {
        $lookup: {
          from: "courses",
          localField: "item",
          foreignField: "email",
          as: "students_courses"
        }
      },
      {
        "$lookup": {
          "from": "instructors",
          "localField": "students_courses._id",
          "foreignField": "courses",
          "as": "students_courses"
        }
      },
      {
        "$set": {
          "_id": "$_id",
          "value": {
            "name": {
              "$concat": [
                "$name.first",
                " ",
                "$name.last"
              ]
            },
            "numbercourses": {
              "$size": "$students_courses"
            }
          }
        }
      },
      {
        "$project": {
          "_id": 1,
          "value": 1
        }
      }
    ])
    

    第一阶段是两个集合的连接,其中指定的字段并分类为一个名为students_courses 的字段。 然后,从students_courses_ids 再次加入。

    使用数据,您可以创建一个名为 value 的字段,并计算其他字段中的课程数。

    $project 仅显示您想要的字段。

    查看示例here

    【讨论】:

      【解决方案2】:
      db.students.aggregate([
        {
          $lookup: {
            from: "courses",
            localField: "_id",
            foreignField: "students",
            as: "students_courses"
          }
        },
        {
          $project: {
            _id: 1,
            value: {
              name: {
                $concat: [
                  "$name.first",
                  " ",
                  "$name.last"
                ]
              },
              numbercourses: {
                "$size": "$students_courses"
              }
            }
          }
        }
      ])
      

      【讨论】:

      • 感谢您提供答案。您能否编辑您的答案以包括对您的代码的解释?这将有助于未来的读者更好地了解正在发生的事情,尤其是那些刚接触该语言并难以理解概念的社区成员。
      猜你喜欢
      • 2023-01-09
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 2015-10-18
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多