Java:连接MongoDB的一些示例

是这样的

首先,这篇主要面向有一些MongoDB经验的.
本来打算在很久之前就整理一下Java连接MongoDB的内容,但是一拖再拖只好现在写了,希望还不算太迟.由于安装实在太过于简单了,所以这里直接讲怎么连接.

1.连接到MongoDB

连接前首先要导入以下两个包,可以在这里找到(点我,点我,快点我啊):

  • bson文件夹下面的:bson-*.jar [*=版本]
  • mongo-java-driver文件夹下面的:mongo-java-driver-*.jar[*=版本]

两个的版本最好是一样的,避免出现问题.

在这里使用的bson和mongo-java-driver版本均是:3.0.1

下面是连接的源码[一定要先启动MongoDB服务器,否则报错!]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
        //连接到mongodb.
    MongoClient mongoClient = new MongoClient();
    /*
    可以上面那样连接,也可以像下面这样去连接[来自官方文档]:
     MongoClient mongoClient1 = new MongoClient();
 MongoClient mongoClient1 = new MongoClient("localhost");
 MongoClient mongoClient2 = new MongoClient("localhost", 27017);
 MongoClient mongoClient4 = new MongoClient(new ServerAddress("localhost"));
 MongoClient mongoClient5 = new MongoClient(new ServerAddress("localhost"), new MongoClientOptions.Builder().build());
 
或者:
MongoClient mongoClient = new MongoClient(Arrays.asList(
   new ServerAddress("localhost", 27017),
   new ServerAddress("localhost", 27018),
   new ServerAddress("localhost", 27019)));
    */
        MongoDatabase db = mongoClient.getDatabase("test");
        System.out.println(db);
        // end.

运行结果如下:

1
2
3
4
May 14, 2015 9:08:03 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
com.mongodb.MongoDatabaseImpl@35f983a6
Process finished with exit code 0

mongodb
image-2278

2.插入数据

插入数据的时候要用到上面的源码,并且要确认MongoDB真实可用[输入命令mongo试试即可].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
        //连接到mongodb.
        MongoClient mongoClient = new MongoClient();
        MongoDatabase db = mongoClient.getDatabase("test");
        // end.
        //--------------------------
        //插入一个文档.
        db.getCollection("restaurants").insertOne(new Document("address"
                , new Document().append("street", "2 Avenue")
                .append("street", "2 Avenue")
                .append("zipcode", "10075")
                .append("building", "1480")
                .append("coord", asList(-73.9557413, 40.7720266)))
                .append("borough", "Manhattan")
                .append("cuisine", "Italian")
                .append("grades", asList(
                        new Document().append("date", "2014-10-01T00:00:00")
                                .append("grade", "A")
                                .append("score", "11"),
                        new Document().append("date", LocalDateTime.now().toString())
                                .append("grade", "B")
                ))
                .append("name", "test").append("restaurant_id", "41704620"));

insertOne(),运行成功之后是没有提示的!!

3.查询结果

查询有多种条件过滤,更多可以参考文档.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//连接到mongodb.
        MongoClient mongoClient = new MongoClient();
        MongoDatabase db = mongoClient.getDatabase("test");
        // end.
        //--------------------------
        FindIterable<Document> iterable =db.getCollection("restaurants").find(eq("borough", "Manhattan"));
        //下面是其他查询方式.[这些方式都可以用new Document替代,但是这样写更加简洁.]
        /*
         db.getCollection("restaurants").find(eq("borough", "Manhattan"));
        db.getCollection("restaurants").find(eq("address.zipcode", "10075"));
        db.getCollection("restaurants").find(gt("grades.score", 30));
        db.getCollection("restaurants").find(lt("grades.score", 10));
        db.getCollection("restaurants").find(and(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));
        db.getCollection("restaurants").find(or(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));
        db.getCollection("restaurants").find().sort(ascending("borough", "address.zipcode"));
        */
        iterable.forEach(new Block<Document>() {
            @Override
            public void apply(final Document document) {
                System.out.println(document);
            }
        });

下面是我的查询结果:

1
Document{{_id=5554bfa96204f509fa8578c3, address=Document{{street=2 Avenue, zipcode=10075, building=1480, coord=[-73.9557413, 40.7720266]}}, borough=Manhattan, cuisine=Italian, grades=[Document{{date=2014-10-01T00:00:00, grade=A, score=11}}, Document{{date=2015-05-14T23:30:49.132, grade=B}}], name=test, restaurant_id=41704620}}

4.更新数据

更新数据,源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//连接到mongodb.
        MongoClient mongoClient = new MongoClient();
        MongoDatabase db = mongoClient.getDatabase("test");
        // end.
        //--------------------------更新一条数据,返回更新条数
        db.getCollection("restaurants").updateOne(
          new Document("name","Juni"),
                new Document("$set",new Document("cuisine",
                        "American (Bew)")).append(
                        "$currentDate",new Document
                                ("lastModified",true)));
        /*
        更新多条数据,使用下面的代码[返回更新条数]:
        db.getCollection("restaurants").updateMany(new Document("address.zipcode", "10016").append("cuisine", "Other"),
        new Document("$set", new Document("cuisine", "Category To Be Determined"))
                .append("$currentDate", new Document("lastModified", true)));
        */

除了上面更新,也可以使用替换(替换将覆盖原文档!!).

1
2
3
4
5
6
7
8
db.getCollection("restaurants").replaceOne(new Document("restaurant_id", "41704620"),
        new Document("address",
                new Document()
                        .append("street", "2 Avenue")
                        .append("zipcode", "10075")
                        .append("building", "1480")
                        .append("coord", asList(-73.9557413, 40.7720266)))
                .append("name", "Vella 2"));

5.删除数据

!!!删除前,一定要做好备份!!

一共有三个删除方式:

  • 1.删除文档
  • 2.删除全部文档
  • 3.删除集合
1
2
3
4
5
6
7
8
9
10
//返回删除数
db.getCollection("restaurants").deleteMany(new Document("borough", "Manhattan"));
/*
删除全部文档[返回删除数]:
        db.getCollection("restaurants").deleteMany(new Document());

删除一个集合:

        db.getCollection("restaurants").drop();
*/

6.聚合查询

下面是一个例子,里面的[$group]、[$sum]均是MongoDB的关键字,可以查阅相应文档获取更多.

1
2
3
4
5
6
7
8
9
    //实在不好意思,我也是写到这才发现toJson返回的数据是格式化过的..
    AggregateIterable<Document> iterable = db.getCollection("restaurants").aggregate(asList(
                new Document("$group", new Document("_id", "$borough").append("count", new Document("$sum", 1)))));
        iterable.forEach(new Block<Document>(){
            @Override
            public void apply(final Document document) {
                System.out.println(document.toJson());
            }
        });

7.索引

下面是两个创建索引的方式:

1
2
3
4
5
db.getCollection("restaurants").createIndex(new Document("cuisine", 1));//创建单个索引

//------------

db.getCollection("restaurants").createIndex(new Document("cuisine", 1).append("address.zipcode", 1));//创建多个索引

源码

上面所有示例的源码.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
    package com.mongodemos;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.time.LocalDateTime;

import static com.mongodb.client.model.Filters.eq;
import static java.util.Arrays.asList;

/**
 * MongoDB -Java常用操作.
 *
 * @author puruidong
 * @version 2015.05.15 00:45
 */
public class Main {
    public static void main(String[] args) {
        //连接到mongodb.
        MongoClient mongoClient = new MongoClient();
        MongoDatabase db = mongoClient.getDatabase("test");
        // end.
        //--------------------------
        //看相应方法调取.
    }

    /**
     * 聚合查询.
     *
     * @param db
     */
    private static void aggFind(MongoDatabase db) {
        AggregateIterable<Document> iterable = db.getCollection("restaurants").aggregate(asList(
                new Document("$group", new Document("_id", "$borough").append("count", new Document("$sum", 1)))));
        iterable.forEach(new Block<Document>() {
            @Override
            public void apply(final Document document) {
                System.out.println(document.toJson());
            }
        });
    }


    /**
     * 删除数据.!慎用!!
     *
     * @param db
     * @return
     */
    private static long deleteData(MongoDatabase db) {
        //返回删除数
        return db.getCollection("restaurants").deleteMany(new Document("borough", "Manhattan")).getDeletedCount();
        /*
        删除全部文档[返回删除数]:
                db.getCollection("restaurants").deleteMany(new Document());

        删除一个集合:

                db.getCollection("restaurants").drop();
        */

    }


    /**
     * 更新文档数据
     *
     * @param db
     * @return
     */
    private static long updateData(MongoDatabase db) {
        return db.getCollection("restaurants").updateOne(
                new Document("name", "Juni"),
                new Document("$set", new Document("cuisine",
                        "American (Bew)")).append(
                        "$currentDate", new Document
                                ("lastModified", true))).getModifiedCount();
        /*
         更新多条数据,使用下面的代码[返回更新条数]:

        db.getCollection("restaurants").updateMany(new Document("address.zipcode", "10016").append("cuisine", "Other"),
        new Document("$set", new Document("cuisine", "Category To Be Determined"))
                .append("$currentDate", new Document("lastModified", true)));



        替换使用下面的代码[替换会覆盖原有数据]:

        db.getCollection("restaurants").replaceOne(
                new Document("restaurant_id","41704620"),
                new Document("address",new Document()
                .append("street","2 Avenue")
                        .append("zipcode","1007")
                        .append("building","1480")
                        .append("coord",asList(-73.9557413,40.7720266))
                .append("name","Vella 2"))
        );

        */

    }

    /**
     * 查询数据.
     *
     * @param db
     */
    private static void findData(MongoDatabase db) {
        FindIterable<Document> iterable = db.getCollection("restaurants").find(eq("borough", "Manhattan"));
        //下面是其他查询方式.[这些方式都可以用new Document替代,但是这样写更加简洁.]
        /*
         db.getCollection("restaurants").find(eq("borough", "Manhattan"));
        db.getCollection("restaurants").find(eq("address.zipcode", "10075"));
        db.getCollection("restaurants").find(gt("grades.score", 30));
        db.getCollection("restaurants").find(lt("grades.score", 10));
        db.getCollection("restaurants").find(and(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));
        db.getCollection("restaurants").find(or(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));
        db.getCollection("restaurants").find().sort(ascending("borough", "address.zipcode"));
        */
        iterable.forEach(new Block<Document>() {
            @Override
            public void apply(final Document document) {
                System.out.println(document);
            }
        });
    }

    /**
     * 通过db对象插入一个集合.
     *
     * @param db
     */
    private static void insertData(MongoDatabase db) {
        //插入一个文档.
        db.getCollection("restaurants").insertOne(new Document("address"
                , new Document().append("street", "2 Avenue")
                .append("street", "2 Avenue")
                .append("zipcode", "10075")
                .append("building", "1480")
                .append("coord", asList(-73.9557413, 40.7720266)))
                .append("borough", "Manhattan")
                .append("cuisine", "Italian")
                .append("grades", asList(
                        new Document().append("date", "2014-10-01T00:00:00")
                                .append("grade", "A")
                                .append("score", "11"),
                        new Document().append("date", LocalDateTime.now().toString())
                                .append("grade", "B")
                ))
                .append("name", "test").append("restaurant_id", "41704620"));


    }
}

嗯,暂时就这些.如果有不明白的可以网上搜索一下MongoDB教程.