Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get an object's array's specific objects with mongo query?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This will work I think, give it a try

dbCollection.find(
            { user: req.user._id, "books.type": type },
            { user: 1, "books.$": 1 }
        )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading