如何使用mongodb在lambda函数中合并两个输出?

时间:2019-08-07 15:31:21

标签: mongodb aws-lambda pymongo

我有两个集合1)个人资料,2)帖子找到以下图片供您参考。 user_prfoile collection

user_posts collection

在lambda函数中,当我传递userid时,我们将获得与userid相关的数据显示。但是我需要在感情数组中提供用户详细信息。

我尝试了下面的代码,但输出为空

def lambda_handler(event, context):

print("Received event: " + json.dumps(event, indent=1))


Userid = event['userid']
uid = ObjectId(Userid)

dispost = list( db.user_posts.aggregate([{ "$match" : { "userid" : uid } }, 
{ "$unwind" : "$user_profile" },
{"$lookup":
    {
        "from" : 'user_profile',
        "localField" : 'feelings.userid',
        "foreignField" : '_id',
        "as" : 'user_details'
    }
},  
{ "$addFields" : { "user_details.feelings.username" : "$user_profile.username", "user_details.feelings.photo" : "$user_profile.photo"}},
{ "$group" :  { 
            "_id" : "$_id", 
            "user_profile" : { 
                "$push" : { 
                        "$arrayElemAt" :  ["$user_details", 0]
}}}}, 
{ "$project" : { "_id" : "$_id", "userid" : 1, "type" : 1, "feelings" : 1 }}
]))
disair = json.dumps(dispost, default=json_util.default)
return json.loads(disair)

我得到一个空的输出。

我需要下面这样的输出。

_id :
userid : 
type : 
location :
feelings : 
   [ {userid : objectid(""),
     username : "nipun",
     photo : " "},
     {userid : objectid(""),
     username : "ramesh",
     photo : " "}
   ] 

在感情数组中,我需要基于感情数组中userid的user_profile集合中的用户详细信息。

1 个答案:

答案 0 :(得分:1)

好的,该聚合查询存在一些问题,大部分问题保持不变,我已经对其进行了修改,到目前为止,请尝试此操作并进行所需的任何更改:

db.getCollection('user_posts').aggregate([{ "$match": { "userid": uid } },
{ "$unwind": "$feelings" },
{
    "$lookup":
    {
        "from": 'user_profile',
        "localField": 'feelings.userid',
        "foreignField": '_id',
        "as": 'feelings'
    }
},
{
    "$group": {
        "_id": "$_id", userPost: { "$first": "$$CURRENT" }, "feelings": {
            "$push": { "$arrayElemAt": ["$feelings", 0] }
        }
    }
}, { "$project": { userid: '$userPost.userid', type: '$userPost.type', "feelings": 1 } }
])