I have tried the following queries and they all return an object that contains an array of all the objects in the array.
dbCollection.find({ user: req.user._id, "books.type": type });
dbCollection.find({ user: req.user._id, books: { $elemMatch: { type } } });
dbCollection.find({ $and: [{ user: req.user._id }, { "books.type": type }] });
dbCollection.find({ user: req.user._id, "books.type": { $in: type } });
dbCollection.find({ user: req.user._id, "books.type": { $in: [type] });
How to get only those objects of array which match the condition instead of whole array?
CodePudding user response:
This will work I think, give it a try
dbCollection.aggregate([
{ $match: { user: { $eq: req.user._id } } },
{
$project: {
user: 1,
books: {
$filter: {
input: "$books",
as: "book",
cond: { $eq: ["$$book.type", type] },
},
},
},
},
]);