带有子查询的 MongoDB $in

标签 mongodb aggregation-framework

我下面有这组合集..

团队集合:

{
   total: 3
   data: [
      {
         "_id": "t1",
         "name": "white horse",
         "leader_id": "L1"
         "teamScore": 12,
         "active": 1
      },
      {
         "_id": "t2",
         "name": "green hornets",
         "leader_id": "L2",
         "teamScore": 9,
         "active": 1
      },
      {
         "_id": "t3",
         "name": "pink flaminggo",
         "leader_id": "L3",
         "teamScore": 22,
         "active": 1
      },
   ]
}

领袖合集:

{
   total: 3
   data: [
      {
         "_id": "L1",
         "name": "John Doe",
         "organization": "Software Development",
         "active": 1
      },
      {
         "_id": "L2",
         "name": "Peter Piper",
         "organization": "Software Development"
         "active": 1
      },
      {
         "_id": "L3",
         "name": "Mary Lamb",
         "organization": "Accounting Department"
         "active": 1
      },
   ]
}

查询应如下所示:SELECT * FROM teams WHERE active = 1 AND leader_id IN (SELECT id FROM leaders WHERE organization = 'Software Development')

我是 mongodb 的新手,我的问题是如何在 mongoDB 聚合框架中转换上面的查询?

最佳答案

您可以使用 $lookup带管道,

  • $match 将检查 active 状态
  • $lookup 将加入 leaders 集合
    • $match 检查 leader_idorganization
  • $match 检查领导者是否[] 为空
  • $project 删除 leaders 字段
db.teams.aggregate([
  { $match: { active: 1 } },
  {
    $lookup: {
      from: "leaders",
      let: { leader_id: "$leader_id" },
      as: "leaders",
      pipeline: [
        {
          $match: {
            $and: [
              { $expr: { $eq: ["$_id", "$$leader_id"] } },
              { organization: "Software Development" }
            ]
          }
        }
      ]
    }
  },
  { $match: { leaders: { $ne: [] } } },
  { $project: { leaders: 0 } }
])

Playground

关于带有子查询的 MongoDB $in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63573853/

相关文章:

mongodb - 对不同结构文档的求和运算

node.js - 通过在 Mongodb 中应用条件,使用 $find 查询嵌套对象

java - 使用 java 和 video.js 从输入流加载视频

mongodb - 如何在symfony2中查询条件为 “like”的mongodb

javascript - 如何在一次查询中获取多个计数?

node.js - mongodb可以查询当月、季度、学期的销售额吗?

c++ - MongoDB C 驱动程序 : how to use regex query collection?

mongodb - Spring mongodb在保存后获取插入项的ID

javascript - MongoDB - 两个多边形的地理空间交集