3.1 MongoDB through the Java

http://mongodb.github.io/mongo-java-driver/3.12/driver/getting-started/quick-start/

3.1.1 connecting

  1. <dependency>
  2. <groupId>org.mongodb</groupId>
  3. <artifactId>mongodb-driver</artifactId>
  4. <version>3.12.7</version>
  5. </dependency>
  1. private ServerAddress serverAddress = new ServerAddress("101.132.251.198", 27017);
  2. private MongoCredential credential = MongoCredential.createCredential("root", "tutorial", "root".toCharArray());
  3. private MongoClient mongoClient = new MongoClient(serverAddress, credential, MongoClientOptions.builder().build());
  4. private MongoDatabase database = mongoClient.getDatabase("tutorial");
  5. private MongoCollection<Document> users = database.getCollection("users");

Create a Document

  1. {
  2. "name" : "MongoDB",
  3. "type" : "database",
  4. "count" : 1,
  5. "versions": [ "v3.2", "v3.0", "v2.6" ],
  6. "info" : { x : 203, y : 102 }
  7. }
  1. Document doc = new Document("name", "MongoDB").append("type", "database")
  2. .append("count", 1)
  3. .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
  4. .append("info", new Document("x", 203).append("y", 102));

Insert a Document

  1. users.insertOne(doc);

Insert Multiple Documents

  1. @Test
  2. public void testInsertMultiple(){
  3. ArrayList<Document> documents = new ArrayList<>();
  4. for (int i = 0; i < 100; i++) {
  5. documents.add(new Document("i", i));
  6. }
  7. users.insertMany(documents);
  8. }

Count Documents in A Collection

  1. @Test
  2. public void testCount() {
  3. System.out.println(users.countDocuments());
  4. }

Query the Collection

Find the First Document in a Collection

  1. @Test
  2. public void testQuery() {
  3. Document myDoc = users.find().first();
  4. System.out.println(myDoc.toJson());
  5. }

image.png

Find All Documents in a Collection

  1. @Test
  2. public void testQuery() {
  3. MongoCursor<Document> cursor = users.find().iterator();
  4. try {
  5. while (cursor.hasNext()){
  6. System.out.println(cursor.next().toJson());
  7. }
  8. }finally {
  9. cursor.close();
  10. }
  11. }

避免用foreach循环迭代遍历,因为如果循环提前结束,应用程序可能会泄露游标

Specify a Query Filter

Get A Single Document That Matches a Filter

  1. @Test
  2. public void testQueryFilter() {
  3. Document myDoc = users.find(Filters.eq("i", 71)).first();
  4. System.out.println(myDoc.toJson());
  5. }

image.png

Get All Documents That Match a Filter

  1. @Test
  2. public void testQueryFilter() {
  3. Block<Document> printBlock = new Block<Document>(){
  4. @Override
  5. public void apply(Document document) {
  6. System.out.println(document.toJson());
  7. }
  8. };
  9. users.find(Filters.gt("i", 50)).forEach(printBlock);
  10. users.find(Filters.and(Filters.gt("i", 50), Filters.lte("i", 100))).forEach(printBlock);
  11. }

Update Documents

  • updateOne
  • updateMany

返回值为UpdateResult,提供了关于文档更新的数量信息

Update a Single Document

  1. @Test
  2. public void testUpdate() {
  3. users.updateOne(Filters.eq("i", 10), new Document("$set", new Document("i", 110)));
  4. Document documents = users.find(new Document("i", 110)).first();
  5. System.out.println(documents.toJson());
  6. }

image.png

Update Multiple Documents

  1. @Test
  2. public void testUpdate() {
  3. // 下面的例子将所有文件的i值增加100,其中i小于100的值:
  4. UpdateResult updateResult = users.updateMany(lt("i", 100), Updates.inc("i", 100));
  5. System.out.println(updateResult.getModifiedCount());
  6. }

Delete Documents

  • deleteOne
  • deleteMany

    1. @Test
    2. public void testDelete() {
    3. DeleteResult deleteResult = users.deleteMany(gte("i", 100));
    4. System.out.println(deleteResult.getDeletedCount());
    5. }

    Create Indexes

  • For an ascending index type, specify 1 for .

  • For a descending index type, specify -1 for .
    1. @Test
    2. public void testCreateIndexes() {
    3. users.createIndex(new Document("i", 1));
    4. }