如何在mongodb中使用聚合来表示数组元素

时间:2017-11-19 08:44:58

标签: mongodb

我有两个集合conversationusercollection

MongoDB格式 对话看起来

[
 {participants:["ram","shyam"], recentchat:"hello shyam"},

 {participants:["ram","hari"], recentchat:"namaste"},

 {participants:["jhon","raju"], recentchat:"what's up"}
]

同样 usercollection 看起来

[
  {"name" : "shyam", "address":"Kathmandu"},

  {"name" : "hari", "address":"Dolakha"},  

  {"name:"jhon", "address":"Pokhara"},

]

假设是:    Ram is the user and it needs to access all the conversation list

我想使用mongodb的aggregate方法加入两个集合,并按以下格式获取结果。

[
  {friend:{name:"shyam",address:"Kathmandu"}, recentchat:"hello shyam"},

  {friend:{name:"hari", address:"Dolakha"},recentchat:"namaste"}    
]

2 个答案:

答案 0 :(得分:1)

会话集合

获取特定用户的近期聊天
var recentChat = db.conversation.find({participants:"shyam"}).sort({$natural:-1}).recentchat

usercollection

中更新该用户的近期聊天
db.usercollection.update({name:"shyam"}, {$set:{ recentchat: recentChat }})

答案 1 :(得分:1)

如果您使用的是MongoDB 3.2+,那么您可以使用$lookup聚合器。

示例:

db.getCollection('conversation').aggregate([
    {$match: {"participants":"ram"}},
    {$lookup: {
        from: "usercollection",
        localField: "participants",
        foreignField: "name",
        as: "friend"
    }},
    {$project: {"friend":1, "recentchat": 1, "_id":0}}
]);

我用:

  • $match - 用于选择父文档。
  • $lookup - 用于从usercollection集合
  • 收集数据
  • $project - 用于定义哪些字段必须包含在文档中