I’m looking to use mongoose to find a document based on a query that finds two property values within an object which is in an array. I used the code shown below but it didn’t work as expected – it returned documents that contained "kiosk" in the name and also any equipment item in the array that had a count of 3. I want it to only return documents with an equipment name of kiosk and only if it has 3 kiosks. Can anyone assist?
if (equipment && equipment !== "All") {
const projects = await Project.find({
$and: [
{
"equipment.name": "kiosk",
"equipment.count": 3,
},
],
});
res.status(StatusCodes.OK).json({ projects });
return;
}
All I’ve tried so far is what I’ve shown. Any suggestions would be appreciated.
2
Answers
I think you should use $elemMatch operator in mongoose. This used to query array elements that match multiple record.
const projects = await Project.find({ equipment: { $elemMatch: { name: "kiosk", count: 3, }, }, });
Your current query is close, but the use of
$and
is not necessary in this case since you’re specifying multiple conditions for the same field. You can directly use an object with multiple properties inside thefind
method.Update:
If you want to ensure that only the equipment item with the name "kiosk" has a count of 3, you can use the
$elemMatch
operator to specify conditions on elements within an array.