MongoDB finding a speciffic document?

二次信任 提交于 2019-12-06 16:43:23

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!