java - MongoDB 在过滤器中返回指定文档

标签 java arrays mongodb document mongo-java

我有这个文档Main doc 它包含名为reviews array of doc reviews 的文档数组

我尝试使用此代码来获取 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/

相关文章:

java - 如何将 SDP 文件与 VLCJ 一起使用

javascript - JavaScript 中的 eval 方法

java - 将 for 循环结果保存为字符串

arrays - Powershell:从get-wmiobject win32_product过滤不需要的值

node.js - 升级到最新的mongodb

java - 通过shell脚本运行maven项目和python文件

java - 显示自定义 map 并在 map 上放置图钉/图像

java - MySQL EntityManager 范围查询

php - 安装 Mongo

node.js - 应如何设置高需求应用程序的 node.js 堆栈?