MongoDB
 sql >> Base de données >  >> NoSQL >> MongoDB

agrégat mongoose comment mapper plusieurs collections dans un tableau

Pour ce genre de situation, $facet aider à catégoriser les données entrantes

db.Collection_A.aggregate([
  { $unwind: "$includes },
  {
    "$facet": {
      "joinB": [            
        {
          "$lookup": {
            "from": "Collection_B", "localField": "includes.includes_id",
            "foreignField": "_id", "as": "includes.includes_list"
          }
        },
        {
          "$group": {
            "_id": "$_id",
            "name": { "$first": "$name" },
            includes: { $push: "$includes" }
          }
        }
      ],
      "joinC": [            
        {
          "$lookup": {
            "from": "Collection_C", "localField": "includes.includes_id",
            "foreignField": "_id", "as": "includes.includes_list"
          }
        },
        {
          "$group": {
            "_id": "$_id",
            "name": { "$first": "$name" },
            includes: { $push: "$includes" }
          }
        }
      ],
      "joinD": [
        {
          "$lookup": {
            "from": "Collection_D", "localField": "includes.includes_id",
            "foreignField": "_id", "as": "includes.includes_list"
          }
        },
        {
          "$group": {
            "_id": "$_id",
            "name": { "$first": "$name" },
            includes: { $push: "$includes" }
          }
        }
      ],
      
    }
  },
  {
    $project: {
      combined: {
        "$concatArrays": [ "$joinB", "$joinC", "$joinD" ]
      }
    }
  },
  { "$unwind": "$combined" },
  {
    "$replaceRoot": { "newRoot": "$combined" }
  },
  {
    "$project": {
      _id: 1,
      name: 1,
      includes: {
        $filter: {
          input: "$includes",
          cond: {
            $ne: [ "$$this.includes_list",[] ]
          }
        }
      }
    }
  }
])

Travail Mongo playground

Remarque :Je pense que c'est une sorte d'anti-modèle que vous suivez. Si vous êtes au début du projet, mieux vaut changer la structure si je ne me trompe pas.