How to combined two output in lambda function using mongodb?

时光总嘲笑我的痴心妄想 提交于 2020-01-06 06:38:43

问题


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

user_posts collection

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 get an empty output.

I need output like this below.

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

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


回答1:


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


来源:https://stackoverflow.com/questions/57397863/how-to-combined-two-output-in-lambda-function-using-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!