1

How can i perform $lookup in aggregate (mongodb) for an array

{
     messages: [{
            "_id" : ObjectId("5bfc43f2bbc4176ecc1c5f83"),
            "text" : "text1",
            "sender" : {
                    "id" : "36046fc2e70dd508a0bf1f36fd2daa20"
            }
         }, {
            "_id" : ObjectId("5bfc43f2bbc4176ecc1c5f83"),
            "text" : "text2",
            "sender" : {
                    "id" : "36046fc2e70dd508a0bf1f36fd2daa22"
            }
    }],
    "filed1": { ... },
    "filed2": { ... }
}

how can i do a $lookup for sender id from accounts collection?

tried:

...
      {
        $lookup: {
          from: "accounts",
          localField: "messages.sender.id",
          foreignField: "id",
          as: "messages.sender.user"
        }
      }
...
13
  • 1
    Does the answer works for you? Commented Nov 29, 2018 at 18:13
  • 1
    Not sure what you are asking. But if the below answer works for you then please accept it and If you have any further doubts then please ask a new question in separate thread. Commented Nov 30, 2018 at 7:33
  • 1
    I can't create new thread but its ok Why? I will surely help you. Commented Nov 30, 2018 at 7:37
  • 1
    Pushing all the document in a single array in a $group stage is not a good job. It will breach the BSON limit of 16 MB. I have upvoted your one question try now to ask. Commented Nov 30, 2018 at 7:45
  • 1
    I cannot understand. Please edit your question and put the whole explanation to it. Commented Nov 30, 2018 at 7:48

1 Answer 1

2

You can use below aggregation

db.collection.aggregate([
  { "$unwind": "$messages" },
  { "$lookup": {
    "from": "accounts",
    "localField": "messages.sender.id",
    "foreignField": "id",
    "as": "messages.sender.user"
  }},
  { "$unwind": "$messages.sender.user" }
  { "$group": {
    "_id": "$_id",
    "messages": { "$push": "$messages" },
    "filed1": { "$first": "$filed1" },
    "filed2": { "$first": "$filed2" }
  }}
])
Sign up to request clarification or add additional context in comments.

Comments

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.