为了账号安全,请及时绑定邮箱和手机立即绑定

Mongodb java 怎样连接

Mongodb java 怎样连接

互换的青春 2019-05-11 13:07:33
Mongodb java 怎样连接
查看完整描述

2 回答

?
开满天机

TA贡献1786条经验 获得超12个赞

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

public class MongoDBJDBC {

    public static void main(String[] args) {

        try {

            // 实例化Mongo对象,连接27017端口

            Mongo mongo = new Mongo("localhost", 27017);

            // 连接名为yourdb的数据库,假如数据库不存在的话,mongodb会自动建立

            DB db = mongo.getDB("test");

            // Get collection from MongoDB, database named "yourDB"

            // 从Mongodb中获得名为yourColleection的数据集合,如果该数据集合不存在,Mongodb会为其新建立

            DBCollection collection = db.getCollection("test1");

            // 使用BasicDBObject对象创建一个mongodb的document,并给予赋值。

            BasicDBObject document = new BasicDBObject();

            //document.put("id", 1001);

            //document.put("msg", "hello world mongoDB in Java");

            // 将新建立的document保存到collection中去

            //collection.insert(document);

            // 创建要查询的document

            BasicDBObject searchQuery = new BasicDBObject();

            searchQuery.put("name", "chen");

            // 使用collection的find方法查找document

            DBCursor cursor = collection.find(searchQuery);

            // 循环输出结果

            while (cursor.hasNext()) {

                System.out.println(cursor.next());

            }

            System.out.println("Hello World");

        } catch (UnknownHostException e) {

            e.printStackTrace();

        } catch (MongoException e) {

            e.printStackTrace();

        }

    }

}

 




查看完整回答
反对 回复 2019-05-12
  • 2 回答
  • 0 关注
  • 776 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信