2017-09-24 12 views
0

私はルックアップを行い、anotheテーブルと1つのサブクエリを結合する必要があります。 サブクエリには一致するcolunmがあります。mongo aggegateテーブルを使ったサブクエリ/カーソルの検索

var ids= // subquery/cursor which will have customer and average; 
    db.user.aggregate([ 

     { "$unwind": "$ids" }, 
     {$lookup: 
     { 
      from: "ids", 
      localField: "customer", 
      foreignField: "customer", 
      as: "average" 
     } 
    } 
    ],function (err, result) { 
     console.log(result); 
     res.json(result); 
    }); 
}); 

私は今、私はusedetails表に、この平均値を示す必要がある

userid average 
1  67 
2  56 
3  40 

を返します平均FOMのuseravrageテーブルを見つけるfoのクエリを持っている私の問題は私です

userid username average 
1  lijo  67 
2  jh  56 
3  ghj  40 

を選択拳のuseaveageはテーブルではありません。オブジェクト

+0

あなたのユーザーコレクションのファイルと平均を追加してください。また、ユーザーと平均が1対1,1対多の関係にあることを伝えますか? –

答えて

0

の配列を与える その別のクエリでは、あなたは、パイプライン内の平均的なクエリを実行し、戻って地元のコレクションに結果を結合するための今後3.6(現在は3.5.13 devに)バージョンの新lookup pipelineバリアントを使用することができます。トップレベルにaverageを移動する$replaceRoot & $mergeObjects続いてユーザID毎に平均値を計算するサブクエリを提供すること

$lookupパイプライン。

db.userdetails.aggregate([ 
    { 
    "$lookup": { 
     "from": "useraverage", 
     "let": { 
     "userid": "$userid" 
     }, 
     "pipeline": [ 
     { 
      "$match": { 
      "$expr": { 
       "$eq": [ 
       "$userid", 
       "$$userid" 
       ] 
      } 
      } 
     }, 
     rest of your subquery 
     ], 
     "as": "average" 
    } 
    }, 
    { 
    "$replaceRoot": { 
     "newRoot": { 
     "$mergeObjects": [ 
      { 
      "$arrayElemAt": [ 
       "$average", 
       0 
      ] 
      }, 
      "$$ROOT" 
     ] 
     } 
    } 
    }, 
    { 
    "$project": { 
     "average": 0 
    } 
    } 
])