我尝试使用此代码来获取 Théo 发布的评论,但它不断向我返回整个文档(包括评论中的子文档),而不是我使用过滤器指定的文档。
Document document = collection.find(Filters.and(Filters.eq("reviews.reviewer_name", "Théo"))).first();
我真的不明白如何只获取这个特定的文档。感谢您的帮助
最佳答案
如果您尝试执行子文档查询并仅检索特定的子文档,则无法使用 mongo 的简单查询来做到这一点。但是,您可以使用聚合管道来实现此目的。
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' } }
])
这将返回一个具有 reviewer
属性的对象数组,每个元素包含一个评论。然后,您可以使用分页阶段来修剪结果:
db.collection.aggregate([
// ... same stages as above, and then:
{ $limit: 1 },
])
不确定您正在使用的 Java 驱动程序的具体数据结构是什么,但这些是可以解决问题的通用 mongo 查询。
如果您想了解有关聚合管道的更多信息,我建议您查看 official documentation这太棒了,我整天都打开它。他们应该有一些 Java 示例。
祝你好运!
关于java - MongoDB 在过滤器中返回指定文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58922810/