Search code examples
javamongodbquerying

MongoDB finding a speciffic document?


I'm struggling to find a specific document, as most tutorials are outdated, and my MongoDB version (the latest) does not have BasicDBObject.

I'm using BSON, here is my attempt,

    public Document getPlayer(UUID uuid) {
    Document toFind = new Document("id", uuid);
    MongoCursor<Document> c = players.find(toFind).iterator();
    while (c.hasNext()) {
        if (toFind.equals(c)) {
            return c;
        }
    }

    return null;
}

I'm fully aware this is wrong, but I just do not know how to find any information on MongoDB.


Solution

  • Look at http://mongodb.github.io/mongo-java-driver/3.9/javadoc/index.html?overview-summary.html

    For normal queries, use the Filters utility class

    players.find(Filters.eq("id", id))
    

    Edit after comment: as I find a green hook on this answer, I guess you already solved it, but nevertheless: make sure, that you include the correct driver version in your project. Specifically, you need a driver of the 3.x series to use the more modern interface.

    The current maven dependency is:

    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.9.1</version>
    </dependency>
    

    Filters fully qualified is actually com.mongodb.client.model.Filters.