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

$lookup verschachteltes Array in mongodb

Wenn Sie Mongodb-Version 3.6 haben dann können Sie es mit verschachteltem $lookup versuchen Aggregation...

db.collection.aggregate([
  { "$lookup": {
    "from": Albums.collection.name,
    "let": { "albums": "$albums" },
    "pipeline": [
       { "$match": { "$expr": { "$in": [ "$_id", "$$albums" ] } } },
       { "$lookup": {
         "from": Songs.collection.name,
         "let": { "songs": "$songs" },
         "pipeline": [
           { "$match": { "$expr": { "$in": [ "$_id", "$$songs" ] } } }
         ],
         "as": "songs"
       }}
     ],
     "as": "albums"
  }}
 ])

Und für langatmige Erklärungen können Sie durch $lookup mehrere Ebenen ohne gehen $entspannen?

Oder wenn Sie eine Mongodb-Version vor 3.6 haben

db.collection.aggregate([
  { "$lookup": {
    "from": Albums.collection.name,
    "localField": "albums",
    "foreignField": "_id",
    "as": "albums"
  }},
  { "$unwind": "$albums" },
  { "$lookup": {
    "from": Songs.collection.name,
    "localField": "albums.songs",
    "foreignField": "_id",
    "as": "albums.songs",
  }},
  { "$group": {
    "_id": "$_id",
    "name": { "$first": "$name" },
    "started_in": { "$first": "$started_in" },
    "active": { "$first": "$active" },
    "country": { "$first": "$country" },
    "albums": {
      "$push": {
        "_id": "$albums._id",
        "title": "$albums.title",
        "released": "$albums.released",
        "type": "$albums.type",
        "songs": "$albums.songs"
      }
    }
  }}
])