1

when i call $lookup it return array but my requirment in only one object. is there any way where i'll get only one object. i have to put $lookup value in $group.

 Message.aggregate(

            {$match:{$or:[{"sender":userId},{"receiver":userId}]}},          
            { $lookup: {from: 'users', localField: 'senderId', foreignField: '_id', as: 'from'} },

            {$sort:{messageTimeStamp:-1}},
            {
                $group:{"_id":
                {
                  "name":
                      }
                     $cond:[
                         {
                             $eq:["$receiver",userId]
                         },
                         {$concat:["$receiver"," and ","$sender"]},
                         {$concat:["$sender"," and ","$receiver"]}
                     ]
                  }
                },"message":{$first:"$message"},
                   "time":{$first:"$messageTimeStamp"},
                   "name":{$first:{
                     $cond:[
                         {
                              $eq:['$receiver',userId]
                        },
                         "$from"
                     ]
                  }},
                }
            },

1 Answer 1

4

The $unwind should help you.

Deconstructs an array field from the input documents to output a document for each element.

$unwind (aggregation)

Sign up to request clarification or add additional context in comments.

2 Comments

with $unwind kind of parse object like $user1.name
$from.name. Take a look on the "as" parameter at the $lookup

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.