I would like to find a single document matching the courseID but inside the document only objects from the materials array whose moduleNo matches the one I give. But the query I currently use seems to return the correct document but also returns all the objects in materials array. Any help would be appreciated.
My schema,
const materialSchema = new mongoose.Schema({
courseID: String,
materials: [
{
moduleNo: Number,
moduleMaterial: String,
},
],
});
My code/query,
exports.getMaterials = (req, res) => {
const { courseID, moduleNo } = req.query;
Material.findOne(
{ courseID, "materials.moduleNo": moduleNo },
(err, result) => {
if (err) {
console.error(err);
} else {
res.json(result);
}
}
);
};
2
Answers
Use the
$elemMatch
operator, something lik this:Update: To return all matching elements in the array, you will have to use an aggregation pipeline, having
$filter
stage, to filter out array elements. Like this:Here’s the playground link.
Way 1 : Use $elemMatch operator in project field
syntax :
https://mongoplayground.net/p/HKT1Gop32Pq
Way 2 : Array Field Limitations array.$ in project field
*
https://mongoplayground.net/p/Db0azCakQg9
Update : Using MongoDB Aggregation
will return output as :
And If you want to format output :
will return result as :
https://mongoplayground.net/p/vdPVbce6WkX