简体   繁体   中英

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.

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

{
  "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

{
  "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; 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 . You can do this by two methods:

  • Write your own custom mapper function/class to map Document to Teams
  • You can eliminate the use of Document to make use of your POJO Teams instead with some modification of your POJO as follows:

Teams.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

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

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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