MongoDB $ com subconsulta

Aug 25 2020

Eu tenho esse conjunto de coleção abaixo ..

coleção de times:

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

coleção 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
      },
   ]
}

A consulta deve ser semelhante a esta: SELECT * FROM teams WHERE active = 1 AND leader_id IN (SELECT id FROM leaders WHERE organization = 'Software Development')

Eu sou novo no mongodb e minha pergunta é como a consulta acima pode ser convertida no framework de agregação mongoDB?

Respostas

1 turivishal Aug 25 2020 at 14:27

Você pode usar $ lookup com pipeline,

  • $matchirá verificar o activestatus
  • $lookup vai se juntar à coleção de líderes
    • $matchpara verificar leader_ideorganization
  • $matchverificar os líderes não está []vazio
  • $projectremover o 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 } }
])

Parque infantil