我从mysql迁移到mongodb。现在,我感到困惑的是,如何将模式下面的内容转换为MongoDB,或者如何查询大学的课程。mysql:
college(college_id,name)
course_college(college_id,course_id)
course(course_id,name)mongo:
高校馆藏
{
"college_id" : "1",
"name" : "Oxford ",
}关系:
{
"college_id" : "1",
"course_id" : "1",
}, {
"college_id" : "9",
"course_id" : "67",
},课程收集
{
"course_id" : "1",
"name" : "Master of Computer Applications ",
}
{
"course_id" : "2,
"name" : "Bachelor of Computer Applications ",
}我需要猫鼬查询在大学获得课程为这种关系。然后我将转换为非关系模式。
发布于 2014-08-24 13:36:13
MongoDB不是关系数据库,所以当您拥有关系数据时,它并不是一种合适的技术。当您决定从关系数据库迁移到MongoDB (通常不是一个好主意)时,您需要改变数据结构的方式。
文档数据库中的关系集合通常不是一个好主意,因为来自多个集合的数据不能在单个查询中完成,就像在关系数据库中使用联接一样。
一个更好的解决方案是在你的大学文档中创建一个数组字段,其中包含大学提供的所有课程,或者在你的课程文档中创建一个数组字段,嵌入所有的学院。您所选择的选项取决于您的应用程序中哪个用例更重要:列出一所学院的所有课程,或者列出所有提供它的学院的课程。当这两种用例都很重要时,您可以考虑两者兼而有之。
请注意,您不一定需要嵌入整个文档。您的选项包括嵌入整个文档,只嵌入最重要的嵌入字段(只嵌入_id ),以便通过一个额外的查询获得所有进一步的信息。在这方面,您所做的选择取决于需要哪些子文档字段来完成最常见的用例。
发布于 2014-08-24 14:46:42
谢谢你@Philipp
在这里,MongoDB的工作方式类似于MySQL关系。
我想办法解决我的紧急情况
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CollegeSchema = mongoose.Schema({
college_name : String
});
var College = mongoose.model('College', CollegeSchema);
var CourseCollegeSchema = mongoose.Schema({
college_id : {type: Schema.ObjectId, ref: 'College' }
, course_id : {type: Schema.ObjectId, ref: 'Course' }
});
var CourseCollege = mongoose.model('CourseCollege', CourseCollegeSchema);
var CourseSchema = mongoose.Schema({
course_name : String
});
var Course = mongoose.model('Course', CourseSchema);查询
// For searching colleges related to a course
CourseCollegeSchema.find({college_id:"53f9ee7ac3130d4816b858ef"}).populate('course_id').exec(function(err, courses){console.log(courses);})
// For searching colleges related to a course
CourseCollegeSchema.find({course_id:"53f9efe4b6ba1a8022f6acdd"}).populate('college_id').exec(function(err, colleges){console.log(colleges);})https://stackoverflow.com/questions/25472166
复制相似问题