2017-03-17 65 views
0

第一個集合:transactions如何加入兩個收集類似像內的MongoDB在mysql中加入

{ 
    "_id": "QH2yYgJyE8A1zKBAWTv_T0VmvceS5l7p15Lki_i2PwfGoV3kHzkeqa6yFFm5oLhwriF39bAl2b4wgSIkvwy-MA", 
    "rate": [ 
    { 
     "user_id": ObjectId("58aeb5bd21b8ae596d3c9869"), 
     "rate": "4", 
     "option": "QUICK_BITE", 
     "message": "Good" 
    } 
    ] 
} 

第二集:users

{ 
    "_id": ObjectId("58aeb5bd21b8ae596d3c9869"), 
    "username": "ravi", 
    "profile": { 
    "firstname": "Ravi", 
    "lastname": "Kumar", 
    "email": "[email protected]", 
    "phone_no": "", 
    "company_name": "gmail", 
    "image": "" 
    } 
}, 
{ 
    "_id": ObjectId("58c104da21b8aeac733c9869"), 
    "username": "", 
    "profile": { 
    "firstname": "lalit", 
    "lastname": "sharma", 
    "email": "[email protected]", 
    "phone_no": "", 
    "company_name": "" 
    } 
}, 
{ 
    "_id": ObjectId("58c12afc21b8aef8553c9869"), 
    "username": "", 
    "profile": { 
    "firstname": "Aijaz", 
    "lastname": "Haidar", 
    "email": "[email protected]", 
    "phone_no": "", 
    "company_name": "yahoo", 
    "image": "" 
    } 
} 

我想加入users收集與transactions收集,以便我應該得到用戶完整的配置文件詳細信息費率。

輸出像

{ 
    "_id" : ObjectId("58c1200321b8ae2d413c98a5"), 
    "rate" : [ 
     { 
      "rate" : "4", 
      "option" : "QUICK_BITE", 
      "message" : "Good", 
      "profile" : { 
       "firstname" : "Ravi", 
       "lastname" : "Kumar", 
       "email" : "[email protected]", 
       "phone_no" : "", 
       "company_name" : "gmail", 
       "image" : "" 
      } 
     } 
    ] 
} 

現在我以下列方式合併使用$lookup兩個集合:

db.transactions.aggregate([ 
    {$lookup: { 
      from: "users", 
      localField: "rate.user_id", 
      foreignField: "_id", 
      as: "profile" 
     }} 
]); 

但上面的查詢不工作:(

+3

嘗試'db.transactions.aggregate([{$放鬆: 「$率」},{ $查找:{ 從 「用戶」, localField: 「rate.user_id」, foreignField: 「_id」 , as:「profile」 }} ]);'More here https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#unwind-example – Veeram

+0

您的輸出結果有點偏離,你是否想要在'rate'數組對象中嵌入'profiles'鍵? – chridam

+0

不,它不是強制性的,但會有1:m的關係,所以我想所有的用戶都應該被映射 –

回答

0

這對我很有用

db.transactions.aggregate([ 
    { 
     $match: { "name": "The Mean Fiddler" } 
    }, 
    { 
     $unwind: "$rate" 
    }, 
    { 
     $lookup: 
     { 
     from: "users", 
     localField: "rate.user_id", 
     foreignField: "_id", 
     as: "userInfo" 
    } 
    },{$unwind:"$userInfo"},{$unwind:"$userInfo.profile"}, 
    {$project:{ 
     "_id":1, 
     "rate":[{ 
      'rate':"$rate.rate", 
      'option':"$rate.option", 
      'message':"$rate.message", 
      'profile' : { 
       'firstname' : "$userInfo.profile.firstname", 
       'lastname' :"$userInfo.profile.lastname" , 
       'email' : "$userInfo.profile.email", 
       'phone_no' : "$userInfo.profile.phone_no", 
       'company_name' : "$userInfo.profile.company_name", 
       'image' : "$userInfo.profile.image", 
      }, 
     }] 
    }} 
])