1

我已經查詢:貓鼬查詢與項目和過濾

Model.aggregate([{ 
     $lookup: { 
      from: 'translations', 
      localField: '_id', 
      foreignField: 'item_id', 
      as: 'translation' 
     }, 
    }, { 
     $project: { 
      "label": "$label", 
      "items": "$items", 
      "translation": { 
       "$filter": { 
        "input": "$translation", 
        "as": "page", 
        "cond": { 
         "$eq": ["$$page.lang_key", lang] 
        } 
       } 
      } 
     } 
    }]) 

而且結果:

[ { _id: 58b2ca5b9ac42bac7aaed48a, 
    label: 'Main', 
    items: [ [Object] ], 
    translation: [ [Object] ] } ] 

如何使這樣字段translation不是一個數組? 因爲我總是接收只有一個數組元素...

回答

1

因爲只接收陣列中的一個元件,既可以使用$unwind$arrayElemAt拼合陣列和產生子文檔。對於後者,像下面這樣的東西應該適合你:

Model.aggregate([ 
    { 
     "$lookup": { 
      "from": "translations", 
      "localField": "_id", 
      "foreignField": "item_id", 
      "as": "translation" 
     } 
    }, 
    { 
     "$project": { 
      "label": 1, "items": 1, 
      "translation": { 
       "$arrayElemAt": [ 
        { 
         "$filter": { 
          "input": "$translation", 
          "as": "page", 
          "cond": { "$eq": ["$$page.lang_key", lang] } 
         } 
        }, 
        0 
       ] 
      } 
     } 
    } 
]) 
+1

很多很多謝謝它的工作!))) –