How to combined two output in lambda function usin

2019-08-18 03:16发布

问题:

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