Py学习  »  MongoDB

MongoDB Java使用多个过滤器并获取最后一个

Usr • 4 年前 • 549 次点击  

在我的收藏中,文档如下所示:

enter image description here

我已通过执行以下操作获得最后插入的文档:

collection.find().sort(new Document("date",-1)).first().getDate()

但是现在我需要得到最后一个日期,它有一个特定的值 functionalityName . 我卡住了,因为我不知道如何修改它,以考虑到两个过滤器。我该怎么做?
我在Mongo中查看了多个过滤器,但是由于我不是要查找特定日期,而是要查找更大的日期(最后一个),所以我不知道如何将其与其他过滤器一起指定。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51392
 
549 次点击  
文章 [ 2 ]  |  最新文章 4 年前
aSlug
Reply   •   1 楼
aSlug    4 年前

连接 find , sort 如此这般肯定行得通, 但是 只有 find() 实际上是在数据库端执行的,它将返回结果,然后应用程序将对其应用排序。

如果要创建一个查询来执行数据库端的所有操作,则需要 pipeline . 要做到这一点,你可以使用 Aggregation Framework java驱动程序的

collection.aggregate(
      Arrays.asList(
              match(eq("functionalityName", "specificValue")),
              sort(descending("date")),
              project(fields(include("date")))
      )
)

In the documentation 您可以找到可以应用于管道的所有阶段。

sheilak
Reply   •   2 楼
sheilak    4 年前

听起来您需要一个过滤器和一个排序,查询将如下所示:

collection.find(Filters.eq("functionalityName", "specificValue"))
          .sort(new Document("date",-1))
          .first()
          .getDate()

所以 sort 部分保持原样,但在 find 添加过滤器的部分。

您还需要导入Filters类:

import com.mongodb.client.model.Filters.*;

或者,您可以导入 Filters 为了简洁起见,静态地初始化 the examples in the official Filters documentation 已完成,如果需要添加其他筛选器,您可能需要签出。

import static com.mongodb.client.model.Filters.*;

// ...

collection.find(eq("functionalityName", "specificValue"))
      .sort(new Document("date",-1))
      .first()
      .getDate()