简体   繁体   English

检索所有 mongoDB 文档并存储在列表中

[英]Retrieve all mongoDB documents and store in a List

I am trying to create a function that retrieves all documents in my mongoDB collection and stores them in an array and returns that array.我正在尝试创建一个 function 检索我的 mongoDB 集合中的所有文档并将它们存储在一个数组中并返回该数组。

getAll()得到所有()

    public static List<Teams> getAll() {
        MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
        //MongoClient mongoClient = new MongoClient("localhost",27017);
        MongoDatabase db = mongoClient.getDatabase("teamDB");
        MongoCollection<Document> coll = db.getCollection("teamCollection");
        
        FindIterable<Document> iterDoc = coll.find();
        Iterator it = iterDoc.iterator();
        ArrayList<Teams> teamsList = new ArrayList<Teams>();
        
        while(it.hasNext()) {
            Object team = it.next();
            teamsList.add(team);
        }
        return teamsList;
    }

Document1文件1

{
  "team_id": "1",
  "team_name": "Dallas Cowboys",
  "players": [
    {
      "player_id": "18",
      "player_name": "Anthony Brown",
      "age": 28,
      "position": "Cornerback",
      "ranking": 3
    },
    {
      "player_id": "15",
      "player_name": "Will Grier",
      "age": 27,
      "position": "Quarterback",
      "ranking": 15
    },
    {
      "player_id": "14",
      "player_name": "Ezekiel Elliott",
      "age": 27,
      "position": "Running Back",
      "ranking": 21
    }
  ]
}

Document 2文件 2

{
  "team_id": "6",
  "team_name": "Green Bay Packers",
  "players": [
    {
      "player_id": "7",
      "player_name": "Jaire Alexander",
      "age": 25,
      "position": "Cornerback",
      "ranking": 23
    },
    {
      "player_id": "3",
      "player_name": "Krys Barnes",
      "age": 24,
      "position": "Linebacker",
      "ranking": 51
    },
    {
      "player_id": "10",
      "player_name": "Mason Crosby",
      "age": 37,
      "position": "Kicker",
      "ranking": 2
    },
    {
      "player_id": "20",
      "player_name": "Randall Cobb",
      "age": 31,
      "position": "Wide Receiver",
      "ranking": 18
    }
  ]
}

Currently my output displays the documents in my collection as one long string for each document;目前,我的 output 将我收藏中的文档显示为每个文档的一个长字符串; however, I haven't figured out how to store these documents in an array.但是,我还没有弄清楚如何将这些文档存储在一个数组中。

The mapping needs to be done from Document to the arraylist of Teams .需要从Document映射到Teams的 arraylist 。 You can do this by two methods:您可以通过两种方法做到这一点:

  • Write your own custom mapper function/class to map Document to Teams将您自己的自定义映射器函数/类写入 map DocumentTeams
  • You can eliminate the use of Document to make use of your POJO Teams instead with some modification of your POJO as follows:您可以取消使用Document来使用您的 POJO Teams ,而是对您的 POJO 进行一些修改,如下所示:

Teams.java团队.java

public class Teams {

    @BsonProperty(value = "team_id")
    private String teamId;
    @BsonProperty(value = "team_name")
    private String teamName;
    private List<Player> players;

    // getters and setters with builder pattern
    // toString()
    // equals()
    // hashCode()
}

Similarly create Player.java同样创建Player.java

public class Player {

    @BsonProperty(value = "player_id")
    private String playerId;
    @BsonProperty(value = "player_name")
    private Double playerName;

    //Add rest of the properties in a similar way

    // getters and setters with builder pattern
    // toString()
    // equals()
    // hashCode()
}

getAll() - You need to add a CodecRegistry to handle translate the BSON for our POJOs and vice versa getAll() - 您需要添加一个 CodecRegistry 来处理我们的 POJO 的 BSON 转换,反之亦然

public static List<Teams> getAll() {
        ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017");
        CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
        CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);
        MongoClientSettings clientSettings = MongoClientSettings.builder()
                                                        .applyConnectionString(connectionString)
                                                        .codecRegistry(codecRegistry)
                                                        .build();
        MongoClient mongoClient = MongoClients.create(clientSettings)
        MongoDatabase db = mongoClient.getDatabase("teamDB");
        MongoCollection<Teams> coll = db.getCollection("teamCollection", Teams.class);
        List<Teams> teamsList = coll.find();
        return teamsList;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM