MongoDB $ in与子查询 [英] MongoDB $in with subquery

查看:100
本文介绍了MongoDB $ in与子查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面有这套收藏品.

团队收藏:

{
   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处于活动状态的团队= 1 AND Leader_id IN(来自处于领导者的组织位置=软件开发"的SELECT ID)

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

I am new to mongodb and my question is how can the query above be converted in mongoDB aggregation framework?

推荐答案

您可以使用带有管道的$ lookup

  • $ match 将检查活动状态
  • $ lookup 将加入领导者收藏
    • $ match 检查 leader_id 组织
    • $match will check active status
    • $lookup will join leaders collection
      • $match to check leader_id and organization
      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 } }
      ])
      

      游乐场

      这篇关于MongoDB $ in与子查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆