【问题标题】:How to exclude documents that have reference in other collection?如何排除在其他集合中有引用的文档?
【发布时间】:2021-06-30 19:35:55
【问题描述】:

我有一个名为“users”的集合,如下所示

[{
    "_id" : ObjectId("60360581ce8d63116c5ce6fb"),
    "userType" : [
        "STUDENT"
    ],
    "firstName" : "Shourv ",
    "lastName" : "Das",
},

{
    "_id" : ObjectId("6027fdb087d0b94d18611db4"),
    "userType" : [
        "STUDENT"
    ],
    "isVerified" : false,
    "firstName" : "Umor",
    "lastName" : "Ahmed"
},
{
    "_id" : ObjectId("6027fd9587d0b94d18611db3"),
    "userType" : [
        "STUDENT"
    ],
    "isVerified" : false,
    "firstName" : "Razel",
    "lastName" : "Khan",
},
...
]

在这些用户中,有些用户被添加到名为“sectionStudents”的集合中,如下所示。

[{
    "_id" : ObjectId("60d736baee3b6b154ccdcc33"),
    "course" : ObjectId("5ffeec372b2234556439d1da"),
    "section" : ObjectId("6002fae3e58bc750b4394229"),
    "student" : ObjectId("60360581ce8d63116c5ce6fb"),
},

/* 2 createdAt:6/26/2021, 2:36:20 AM*/
{
    "_id" : ObjectId("60d63e44691df002f0e662ed"),
    "course" : ObjectId("5ffeec372b2234556439d1da"),
    "section" : ObjectId("6002fae3e58bc750b4394229"),
    "student" : ObjectId("6027fdb087d0b94d18611db4"),
    
},
{
    "_id" : ObjectId("60d63a9fddcd320314a16470"),
    "course" : ObjectId("5ffeec372b2234556439d1da"),
    "section" : ObjectId("6002fae3e58bc750b4394229"),
    "student" : ObjectId("6027fd9587d0b94d18611db3"),
},
...
]

“sectionsStudents”集合中“用户”的引用是student

我现在的要求是,我想从“users”集合中获取所有未添加到“sectionStudents”集合中“course”的文档。

我怎样才能做到这一点?

【问题讨论】:

  • 您认为提供的答案中是否有某些内容无法解决您的问题?如果是这样,那么请对答案发表评论,以阐明究竟需要解决哪些尚未解决的问题。
  • 非常感谢您的回复,我正在实施您的方法并通知您。
  • @turivishal,如果除了查询如何过滤掉特定课程的特定学生(例如课程 ID“5ffeec372b2234556439d1da”)之外,我将不胜感激。
  • 看看这个playground
  • @turivishal,再次感谢。但它并没有过滤掉我提供的特定课程的学生。相反,它向我展示了所有用户:(

标签: mongodb mongoose aggregation-framework


【解决方案1】:
  • $lookup 使用管道,将 _id 传递给管道,将条件与学生字段匹配并使用 $limit 返回单个文档,因为我们只需要条件文档
  • $match student 应该为空
  • $unset student 我们不需要的字段
db.users.aggregate([
  {
    $lookup: {
      from: "sectionStudents",
      let: { student: "$_id" },
      pipeline: [
        { 
          $match: { 
            $expr: { $eq: ["$$student", "$student"] },
            course: ObjectId("5ffeec372b2234556439d1da")
          } 
        },
        { $limit: 1 }
      ],
      as: "student"
    }
  },
  { $match: { student: [] } },
  { $unset: "student" }
])

Playground

【讨论】:

  • 你拯救了我的一天。你的回答完全没问题。我在代码中输入了错误的集合名称。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2021-09-23
  • 1970-01-01
  • 2018-05-27
  • 2021-12-03
  • 2021-02-16
  • 1970-01-01
  • 2018-07-20
  • 1970-01-01
相关资源
最近更新 更多