MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Mungo-Aggregat, wie mehrere Sammlungen in einem Array abgebildet werden

Für diese Art von Situation $facet helfen, die eingehenden Daten zu kategorisieren

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",[] ]
          }
        }
      }
    }
  }
])

Arbeitender Mongo-Spielplatz

Hinweis:Ich denke, das ist eine Art Anti-Muster, dem Sie folgen. Wenn Sie sich in einem frühen Stadium des Projekts befinden, ändern Sie besser die Struktur, wenn ich mich nicht irre.