I have this document It contains this array of document named reviews
I tried this code to get the review that were posted by Théo but it keeps returning me the whole document (including sub-documents in reviews) not the one I'm specifing by with Filters.
Document document = collection.find(Filters.and(Filters.eq("reviews.reviewer_name", "Théo"))).first();
I really can't understand how to get only this specific document. Thanks for any help
If you're trying to do sub-document queries & only retrieve specific sub-documents, there's no way to do that with mongo's simple queries. However, you can use the aggregate pipeline to achieve this.
db.collection.aggregate([
// This is the same as your initial find query, it will limit the top-level docs to only be the ones you are interested in
{ $match: { 'reviewers.reviewer_name': 'Theo' } },
// You can now unwind the results, which will make all the sub-documents top-level
{ $unwind: '$reviewers' },
// Re-match to filter the reviewers, this will actually drop the unmatched reviewers
{ $match: { 'reviewers.reviewer_name': 'Theo' } },
// Now you can use a projection to get the final results you are looking for
{ $project: { reviewer: '$reviewers' } }
])
This will return an array of objects with a reviewer
property, each element containing a single review. You can then use the pagination stages to trim the results:
db.collection.aggregate([
// ... same stages as above, and then:
{ $limit: 1 },
])
Not sure what the specific data structures would be with the Java driver you are using, but these are the general mongo queries that will do the trick.
If you want to read more about the aggregate pipeline, I recommend checking out the official documentation which is so awesome that I have it opened all day. They should have some Java examples on there.
Best of luck!