2

I have an MongoDB object like:

{
  "user" : ObjectId("60e5f88159292f575c0ca17f"),
  "questions" :[
     {
       question 'aaaaaaa',
       id :'1'
     },
     {  
       question 'bbbbbbb',
       id :'2'
     },
     {
       question 'ccccccc',
       id :'3'
     }
   ]
}

I want to pass an array of questions id ['1', '3'] and user object id. I want to fetch the question which matches the questions id and user.

My expected output should look like this:

{
  "user" : ObjectId("60e5f88159292f575c0ca17f"),
  "questions" :[
     {
       question 'aaaaaaa',
       id :'1'
     },
     {
       question 'ccccccc',
       id :'3'
     }
   ]
}

How can I do this?

1 Answer 1

1

This is one way to achieve this using aggregate.

[
  {
    "$unwind": "$questions"
  },
  // filter out questions
  {
    $match: {
      "questions.id": {
        $in: [
          "1",
          "3"
        ]
      }
    }
  },
  // regroup to original structure
  {
    $group: {
      _id: "$_id",
      questions: {
        $push: "$questions"
      },
      user: {
        $first: "$user"
      }
    }
  }
]

https://mongoplayground.net/p/LQmC6VG4s_S

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.