MongoDB
 sql >> Teknologi Basis Data >  >> NoSQL >> MongoDB

$lookup array bersarang di mongodb

Jika Anda memiliki versi mongodb 3.6 maka Anda dapat mencoba dengan $lookup bertingkat agregasi...

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

Dan untuk penjelasan panjang lebar, Anda dapat membaca $ mencari beberapa level tanpa $bersantai?

Atau Jika Anda memiliki versi mongodb sebelum 3.6

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



  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Diskriminator ambigu 'myType' ketika 'myType' dihasilkan secara dinamis saat dijalankan

  2. MongoDB $eq Aggregation Pipeline Operator

  3. Mongodb C# Driver Kesalahan filter yang tidak didukung dengan predikat linq tertentu

  4. Spring Data MongoDB dan allowDiskUse

  5. $nin dengan $expr