MongoDB-不在其他表中(多对多关系)

MongoDB-不在其他表中(多对多关系),mongodb,Mongodb,我正在学习使用mongodb。我做了3个集合(用户、注册、课程) 每次用户单击其中一门课程时,都会将其添加到报名表中。 我可以为用户显示注册列表,但我不知道如何显示用户未注册的课程 我想知道如何显示用户尚未添加到注册表中的课程? 我试图使用user_id:{$ne:1},但似乎没有显示未注册的正确课程 如何正确显示?使用此集合结构: 步骤1:获取用户的注册课程列表。例如:用户2的课程:['2222'] 步骤2:在课程集合上使用查找查询({courseID:{$nin:['2222']}})获取未

我正在学习使用mongodb。我做了3个集合(用户、注册、课程)

每次用户单击其中一门课程时,都会将其添加到报名表中。 我可以为用户显示注册列表,但我不知道如何显示用户未注册的课程

我想知道如何显示用户尚未添加到注册表中的课程? 我试图使用
user_id:{$ne:1}
,但似乎没有显示未注册的正确课程


如何正确显示?

使用此集合结构:

步骤1:获取用户的注册课程列表。例如:用户2的课程:['2222']

步骤2:在
课程
集合上使用
查找
查询(
{courseID:{$nin:['2222']}}
)获取未注册课程列表

但是,我建议您通过以下任一方式更新集合的架构:

  • 将注册课程ID保存在数组中的
    User
    集合中
  • 将课程保存在
    注册
    集合中的数组中
这样,您可以消除步骤1中的一些处理

希望这有帮助

您可以使用

假设您知道
user\u id
,假设我们选择了具有
user\u id:2

您可以先从
课程
获取所有课程,然后只筛选用户尚未注册的课程

db.Course.aggregate({
  $lookup: { // "join" with Enrollment
    from: "Enrollment",
    localField: "courseID",
    foreignField: "courseID",
    as: "enrollments"
  },
},
{
  $match: { // only match courses that user_id 2 doesn't exist in list of enrolments
    "enrollments.user_id": {
      $ne: 2
    }
  }
})

或者从特定的
用户开始
注册
,然后从
课程

db.Enrollment.aggregate({
  $match: { // find enrolments of user_id 2
    user_id: 2
  }
},
{
  $group: { // combine all courseID into an array
    _id: "$user_id",
    courseIDs: {
      $push: "$courseID"
    }
  }
},
{
  $lookup: { // "join" with Course that is not in the list of enrolments
    from: "Course",
    as: "notEnrolledCourses",
    let: {
      courseIDs: "$courseIDs"
    },
    pipeline: [
      {
        $match: {
          $expr: {
            $not: {
              $in: [
                "$courseID",
                "$$courseIDs"
              ]
            }
          }
        }
      }
    ]
  }
})


请注意,上述方法没有相同的输出结构,您必须操纵以获得所需的输出形状。

@Abishek您的意思是这样的吗
UserCollection:user_id(int)、name(string)、registred[]
registrmentcollection:courseID(int)、courseName(string)、users[]
@sekti92uk如果您在
registration
中没有额外的数据要保存,例如
startDate
,那么使用上述结构比您的问题结构更有利。不过,您只需要将阵列保持在一侧,因此无论是
registered[]
还是
users[]
@sekti92uk是的,我只是想这样。将注册的数组保留在
UserCollection
中。如果您这样做并且没有任何额外字段
已注册
集合。然后您可以删除
已注册的
集合。谢谢。我做了类似的事情,但返回的对象是这样的
如何在flask这样的模板上显示它?您使用哪个库连接到数据库?@thamsada.ts我使用的是flask\u mongoengineI我对python不太熟悉,但由于它返回一个光标,我认为您必须用
list()将其包装起来
@thamsada.ts谢谢,伙计,我已经做了。再次感谢
db.Enrollment.aggregate({
  $match: { // find enrolments of user_id 2
    user_id: 2
  }
},
{
  $group: { // combine all courseID into an array
    _id: "$user_id",
    courseIDs: {
      $push: "$courseID"
    }
  }
},
{
  $lookup: { // "join" with Course that is not in the list of enrolments
    from: "Course",
    as: "notEnrolledCourses",
    let: {
      courseIDs: "$courseIDs"
    },
    pipeline: [
      {
        $match: {
          $expr: {
            $not: {
              $in: [
                "$courseID",
                "$$courseIDs"
              ]
            }
          }
        }
      }
    ]
  }
})