1

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.

Archie
  • 153
  • 12

2 Answers2

2

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.

mtj
  • 3,381
  • 19
  • 30
0

You can easily query mongoDb using Spring Data MongoDB and maven as follows.

First you need to add maven dependency

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Since it allows to map mongoDB document and a java POJO, create a model class.

import org.springframework.data.annotation.Id;
public class Player{
    @Id
    private String id;
    private String playerName;

    //getters and setters
}

Assuming your mongoDb document as follows

{
    "_id": "123456789",
    "playerName":"name1"
}

Then create an interface class as a repository by extending MongoRepository class

public interface PlayerRepository extends MongoRepository<Player, String> {

    Player findById(String id);

    Player findByPlayerName(String playerName);

    @Query("{name:{$regex: ?0,$options:'i'}}")
    List<Player> findPlayerByNameRegex(String name);
}

Finally you can use them Implementing or AutoWiring(recommended) the repository class. Just implement a method naming findByFiledName and remaining will do Spring MongoDb dependency. Additionally you can use @Query annotation for custom queries and filters. Also you can refer the Spring Documentation

Sajith Herath
  • 1,002
  • 2
  • 11
  • 24