如何使用mongodb在lambda函数中合并两个输出? [英] How to combined two output in lambda function using mongodb?

查看:150
本文介绍了如何使用mongodb在lambda函数中合并两个输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two collection 1) profile ,2) posts find the below pic for your reference. user_prfoile collection

user_posts集合

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

In the lambda function, when i passed the userid, then we will get the userid revlevant data display. but i need user details in feelings array.

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

I tried with the below code, but i get the empty output

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)

我得到一个空的输出.

我需要下面这样的输出.

I need output like this below.

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

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

in feelings array , i need user details from user_profile collection based on userid in feelings array.

推荐答案

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

Ok, there are couple of issues with that aggregation query, keeping most of it as is, I've modified it to work, as of now please try this and make any changes needed :

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 } }
])

这篇关于如何使用mongodb在lambda函数中合并两个输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆