sql >> Base de Datos >  >> NoSQL >> MongoDB

Búsqueda de MongoDB cuando el campo externo es una matriz de objetos

Puede usar la siguiente agregación con mongodb 3.6 y superiores

db.resources.aggregate([
  { "$match": { "type": "FUNC" } },
  { "$lookup": {
    "from": "initiatives",
    "let": { "id": "$_id" },
    "pipeline": [
      { "$match": { "$expr": { "$in": ["$$id", "$ressources.function"] } } },
      { "$unwind": "$ressources" },
      { "$match": { "$expr": { "$eq": ["$ressources.function", "$$id"] } } },
      { "$group": {
        "_id": "$ressources.function",
        "participation_sum": { "$sum": "$ressources.participating" }
      }}
    ],
    "as": "result"
  }}
])