1

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?

1 Answer 1

1

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] },
                        },
                    },
                },
            },
        ]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.