鍍金池/ 問答/數(shù)據(jù)庫/ MongoDB數(shù)據(jù)的聚合查詢問題,新手求解?

MongoDB數(shù)據(jù)的聚合查詢問題,新手求解?

有兩個集合:
A集合中存"用戶信息";
B集合中存"文章";

B集合中每篇文章都有一個評論字段如下:

comment:[{
    uid:"59ffd1966e39780ae3fd99c3",
    message:'評論內(nèi)容'
},{
    uid:"59ffd269fbcba4346517c098",
    message:'評論內(nèi)容'
},{
    uid:"59ffd278fbcba4346517c099",
    message:'評論內(nèi)容'
}]

如何在查詢文章評論時,通過uid來關(guān)聯(lián)A集合中的用戶信息,希望返回結(jié)果如下:

comment:[{
    username:"用戶姓名",
    
    ......
    
    message:'評論內(nèi)容'
},{
    username:"用戶姓名",
    
    ......
    
    message:'評論內(nèi)容'
},{
    username:"用戶姓名",
    
    ......
    
    message:'評論內(nèi)容'
}]

不希望在B集合中插入數(shù)據(jù)時,將A集合的數(shù)據(jù)查出再插入,這樣存在數(shù)據(jù)冗余。。。。;
B集合中只放用戶ID,不放其他任何用戶信息。

翻閱MONGODB MANUAL沒有找到。。。。

db.b.aggregate([
    {$unwind: "$comment"},
    {
      $lookup:
        {
          from: "A",
          localField: "comment.uid",
          foreignField: "uid",
          as: "guest"
        }
    },
    {$group : {_id:"$title",comments:{$push:"$comment"}}
]);

返回結(jié)果其實只有 title和comments,其他相關(guān)字段都沒了。。。。

求解!

回答
編輯回答
何蘇葉
db.b.aggregate([
    {$unwind: "$comment"},
    {
      $lookup:
        {
          from: "A",
          localField: "comment.uid",
          foreignField: "uid",
          as: "guest"
        }
    },
    {$group : {_id:"$title",fullDoc:{$push:"$$ROOT"}} // <---將整個文檔放進來
]);

這樣做雖然可以達到你的目的,但是建議你還是考慮一下冗余。這里的數(shù)據(jù)一致性并沒有這么重要。
另外$lookup雖然可以解決問題,但是它的性能并不是很好,并且不支持Sharding,慎用。

2017年5月12日 00:05