MongoDB $ in con subconsulta

Aug 25 2020

Tengo este conjunto de colección a continuación.

colección de equipos:

{
   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
      },
   ]
}

colección de líderes:

{
   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
      },
   ]
}

La consulta debería verse así: SELECT * FROM teams WHERE active = 1 AND leader_id IN (SELECT id FROM leaders WHERE organization = 'Software Development')

Soy nuevo en mongodb y mi pregunta es ¿cómo se puede convertir la consulta anterior en el marco de agregación de mongoDB?

Respuestas

1 turivishal Aug 25 2020 at 14:27

Puedes usar $ lookup con pipeline,

  • $matchcomprobará el activeestado
  • $lookup se unirá a la colección de líderes
    • $matchpara comprobar leader_idyorganization
  • $matchcomprobar líderes no está []vacío
  • $projectpara eliminar el leaderscampo
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 } }
])

Patio de recreo