I'm looking for the solution since yesterday, but can't find it. I tried different approaches like $elemMatch, aggregation etc. but nothing works. Either I get all objects or just the first one, but never only that ones with the matching IDs.
What I try to achieve: Get all objects of an array with one of multiple IDs.
First parameter is the user ID like 60a3f7d0f988f1e57212a81e. Every Document in this collection is unique by the user ID.
Second parameter is an array like ['609d1cfe0806daba1b0502bf', '609d1bba887035b9cd4292aa'] that consists of different IDs to be matched with the objects of the array words.
My approach gets only the first object and doesn't even work with an array of IDs (wordIDs) as parameter.
Words.prototype.getSpecificPersonalWords = async function(userID, wordIDs) {
const words = await personalWords.aggregate([
{$match:
{"user_id": userID}
},
{$unwind:
{"path": "$words"}
},
{$match:
{"words.word_id": { $in: ['609d1cfe0806daba1b0502bf', '609d1bba887035b9cd4292aa'] } }
}
])
return words
}
Document, that I want to query:
{
"_id": {
"$oid": "60a3f7d0f988f1e57212a81e"
},
"user_id": "609d22188ea8aebac56f9dc3",
"__v": {
"$numberInt": "0"
},
"words": [{
"word_id": "609d1bba887035b9cd4292aa",
"last_practiced": "2021-05-15 16:00:00",
"strength": {
"$numberInt": "1"
}
}, {
"word_id": "609d1c35861d99b9effc0027",
"last_practiced": "2021-05-15 16:00:00",
"strength": {
"$numberInt": "1"
}
}, {
"word_id": "609d1dcbc99e8dba538208d7",
"last_practiced": "2021-05-15 16:00:00",
"strength": {
"$numberInt": "1"
}
}]
}
Schema of that document
{
user_id: {
type: String,
unique: true
},
words: Array
});
I hope someone can help me to figure this out. Thanks in advance.