Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
Many To Many with embedded pivot list

I am trying to select all users which references a group that references a permission that has "valid" set to true (possibly multiple). To achieve this I am planning to use an aggregation with a lookup.

db={
  "users": [
    {
      "_id": "1",
      "groups": [
        "2"
      ]
    },
    {
      "_id": "2",
      "groups": [
        "1"
      ]
    }
  ],
  "group": [
    {
      "_id": "1",
      "permissions": [
        "12",
        "3"
      ]
    },
    {
      "_id": "2",
      "permissions": [
        "3",
        "2"
      ]
    }
  ],
  "permission": [
    {
      "_id": "12",
      "valid": true
    },
    {
      "_id": "3",
      "valid": true
    },
    {
      "_id": "2",
      "valid": true
    }
  ]
}

I can't think of an efficient/simple way to do this.

I have 2 ideas:

  1. have a lookup from user to group with a pipeline that does a lookup from group to permission. The problem there is I would need to do a $match to see if the user's group list contains the groups id (which I don't know if its possible)
  2. do a simple lookup from user to group than unwind the joined field and do a second lookup using the joined field from group to permission. Than at the end do a $match to see if any contain "valid" true and group the results back to get the original users. This idea doesnt sound very efficient though. (https://mongoplayground.net/p/JB9Yb3a65Cn)

Any ideas or inputs on this?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

  • you can use direct array of object without $unwind in lookup as localFields,
  • second lookup will replace group field with permissions response because it is not needed in next stage
db.users.aggregate([
  {
    $lookup: {
      from: "group",
      localField: "groups",
      foreignField: "_id",
      as: "group"
    }
  },
  {
    $lookup: {
      from: "permission",
      localField: "group.permissions",
      foreignField: "_id",
      as: "group"
    }
  },
  { $match: { "group.valid": true } },
  { $unset: "group" }
])

Playground

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda