2016-11-22 53 views
4

我想使用MongoDB聚合來填充userscomments。我可以很容易地將它用於與$lookup運算符一起填充createdBy用於填充的聚合查詢

我的問題是有沒有辦法可能使用$each運營商在聚合或類似的東西填充user的評論?

我用Mongo 3.2試過了,但是在某個地方我看過它將會是3.4版本的新功能? 我想轉義使用$unwind$groups(我成功地做到了這一點)和類似的事情,以便查詢不會變成意大利麪代碼。

用戶

{ 
    "_id" : ObjectId("582c31d4afd9252c8515a88b"), 
    "fullName": "test1" 
}, 
{ 
    "_id" : ObjectId("582c3db0afd9252c8515a88d"), 
    "fullName": "test2" 
} 

帖子

{ 
    "_id" : ObjectId("5829cac7e9c0994d3db718f8"), 
    "imgUrl": "images/test.jpg", 
    "createdBy": ObjectId("582c31d4afd9252c8515a88b"), 
    "comments": [ 
     { 
      "_id" : ObjectId("5829cab8e9c0994d3db718f7"), 
      "content": "blabla", 
      "user": ObjectId("582c31d4afd9252c8515a88b") 
     } 
    ] 
} 

預期輸出:的

{ 
    "_id" : ObjectId("5829cac7e9c0994d3db718f8"), 
    "imgUrl": "images/test.jpg", 
    "createdBy": ObjectId("582c31d4afd9252c8515a88b"), 
    "comments": [ 
     { 
      "_id" : ObjectId("5829cab8e9c0994d3db718f7"), 
      "content": "blabla", 
      "user": { 
         "_id" : ObjectId("582c31d4afd9252c8515a88b"), 
         "fullName": "test1" 
        } 
     } 
    ] 
} 
+0

我不明白你的問題。你能否詳細說明一下? – styvane

+0

@Styvane字段'用戶'就像是「FK」,我想重寫'用戶'集合中的所有字段。 這是我想要的結果... https://postimg.org/image/3n9bb9u0p/ –

+0

請問你[編輯鏈接](http://stackoverflow.com/posts/40736869/edit)對你的問題添加預期的輸出(document not image) – styvane

回答

1

如果你想使用MongoDB的聚集功能,那麼你可以使用下面的解決方案。

db.getCollection('posts').aggregate([ 
    {"$unwind":{"path":"$comments","preserveNullAndEmptyArrays":true}}, 
    { $lookup: 
      { 
       from: 'users', 
       localField: 'comments.user', 
       foreignField:'_id', 
       as: 'comments.user' 
      } 
    }, 
    {"$unwind":{"path":"$comments.user","preserveNullAndEmptyArrays":true}}, 
    { 
      $group : { 
       _id : "$_id", 
       comments : {$push : "$comments"}, 
       imgUrl : {$first : "$imgUrl"}, 
       createdBy : {$first : "$createdBy"} 
      } 
    } 

]) 

請確保您有3.2.8或更高版本的MongoDB使用$查找選項

0

使用填入方法貓鼬。

db.collections.find({}).populate([{path:"comments.user"}]). 
+0

我想用本地mongo來做。 –