javamongodbsortingbsonmongo-collection

MongoDB Java use multiple filters and get last


In my collection the documents look like this:

enter image description here

I've managed to get the last inserted document by doing this:

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

But now I need to get the last by date AND that has got a specific value for functionalityName. I'm stuck because I don't know how to modify it to take in consideration both filters. How do I do that?
I had a look at multiple filters in Mongo but since I'm not looking for a specific date but for the greater one (last one), I don't know how to specify that together with other filters.


Solution

  • Sounds like you want one filter and a sort, and the query would look like this:

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

    So the sort part stays as is but in the find part you add the filter.

    You'll also need to import the Filters class:

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

    Alternatively, you can import the Filters class statically for brevity, this is how the examples in the official Filters documentation are done, which you may want to check out if you need to add additional filters.

    import static com.mongodb.client.model.Filters.*;
    
    // ...
    
    collection.find(eq("functionalityName", "specificValue"))
          .sort(new Document("date",-1))
          .first()
          .getDate()