Reputation: 1182
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?
Upvotes: 2
Views: 27
Reputation: 1686
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
Upvotes: 1