我有两个集合conversation
和usercollection
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"}
]
答案 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}}
]);
我用: