【问题标题】:How to write an aggregation query for mongodb using node如何使用节点为 mongodb 编写聚合查询
【发布时间】:2020-05-26 12:27:12
【问题描述】:

我想写一个查询来从 mongodb 中获取数据,我有 3 个集合 --books、teachers、students.Book 集合有 bookName 和_id,teachers 集合有 --_id、teacherName 和teacherId,学生集合有_id 、学生姓名、教师编号……我有 studentName 作为 S1,teacherName 作为 T1,我怎样才能从学生集合中获取名称为 S1 的学生记录,其中的 teacherId 作为名称 T1(来自教师集合)...eg. select _id from student where studentName =S1 and teacherId=(select techerID from techer where teacherName = T1)… how can I write this query in node using agregation

books.aggregate([
  {
    '$match': {
      'name': 'book1'     }
  }, {

    '$lookup': {

{    from :students,
    '$match': {

      'name': 'Annie'     }
  },
      'from': 'teachers', // collection name of the teachers
      'localField': 'teacherId',
      'foreignField': '_id', 
      'as': 'teachers'
    }
  }, {
    '$match': {
      'teachers': {
        '$elemMatch': {
          'teacherName': 'Jones'
        }
      }
    }
  }
])`

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    据我了解,您希望使用学生姓名和教师姓名获取学生记录。

    假设每个学生只有一个teacherId。

    `students.aggregate([
      {
        '$match': {
          'name': 'Anne' // collection name of the students
        }
      }, {
        '$lookup': {
          'from': 'teachers', // collection name of the teachers
          'localField': 'teacherId',
          'foreignField': '_id', 
          'as': 'teachers'
        }
      }, {
        '$match': {
          'teachers': {
            '$elemMatch': {
              'teacherName': 'Jones'
            }
          }
        }
      }
    ])`
    

    【讨论】:

    • 我还想从以名称为名称的书籍集合中获取数据,我已经使用了 books.agregate 和 match 来做到这一点,那么我怎样才能使上面的代码像
    • 是否可以在同一个 lokkup 中使用两个匹配项......就像匹配 annie 以及 john
    • @ Jai ..你能帮帮我吗,根据你的代码,我对我的代码做了一些更改
    猜你喜欢
    • 2019-08-19
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    相关资源
    最近更新 更多