Home > Enterprise >  Mongoose get objects which match an object item from an array of objects
Mongoose get objects which match an object item from an array of objects

Time:06-26

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);
      }
    }
  );
};

CodePudding user response:

Use the $elemMatch operator, something lik this:

exports.getMaterials = (req, res) => {
  const { courseID, moduleNo } = req.query;
  Material.findOne(
    { courseID },
    {"materials": { $elemMatch: {moduleNo: moduleNo}},
    (err, result) => {
      if (err) {
        console.error(err);
      } else {
        res.json(result);
      }
    }
  );
};

CodePudding user response:

Way 1 : Use $elemMatch operator in project field.

The $elemMatch operator limits the contents of an array field from the query results to contain only the first element matching the $elemMatch condition.

syntax :

db.collection.find(query,projection)

db.collection.find({
     "field": field_value                  
  },{
    "array_name":{
       $elemMatch:{"key_name": value }
    },
    field:1,
    field_2:1,
    field_3:0
})

https://mongoplayground.net/p/HKT1Gop32Pq

Way 2 : Array Field Limitations array.$ in project field

db.collection.find({
     "field": field_value,
     "array_name.key_name": value       
  },{
        "array_name.$":1,
        field:1,
        field_2:1,
        field_3:0
 });

https://mongoplayground.net/p/Db0azCakQg9

  • Related