一、驱动包 maven配置
<dependency><groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.2</version>
</dependency>
25 public void testCRUD() throws UnknownHostException {
26 // 连接到mongodb
27 Mongo mongo = new Mongo("localhost", 27017);
28
29 // 打开数据库test
30 DB db = mongo.getDB("test");
31
32 // 遍历所有集合的名字
33 Set<String> colls = db.getCollectionNames();
34 for (String s : colls) {
35 System.out.println(s);
36 // 先删除所有Collection(类似于关系数据库中的"表")
37 if (!s.equals("system.indexes")) {
38 db.getCollection(s).drop();
39 }
40 }
41
42 // 取得集合emp(若:emp不存在,mongodb将自动创建该集合)
43 DBCollection coll = db.getCollection("emp");
44
45 // delete all
46 DBCursor dbCursor = coll.find();
47 for (DBObject dbObject : dbCursor) {
48 coll.remove(dbObject);
49 }
50
51 // create
52 BasicDBObject doc = new BasicDBObject("name", "杨俊明").append("sex", "男")
53 .append("address",
54 new BasicDBObject("postcode", "201202").append(
55 "street", "田林路888号").append("city", "上海"));
56 coll.insert(doc);
57
58 // retrieve
59 BasicDBObject docFind = new BasicDBObject("name", "杨俊明");
60 DBObject findResult = coll.findOne(docFind);
61 System.out.println(findResult);
62
63 // update
64 doc.put("sex", "MALE");// 把sex属性从"男",改成"MALE"
65 coll.update(docFind, doc);
66 findResult = coll.findOne(docFind);
67 System.out.println(findResult);
68
69 coll.dropIndexes();// 先删除所有索引
70 // create index
71 coll.createIndex(new BasicDBObject("name", 1)); // 1代表升序
72
73 // 复杂对象
74 UserData userData = new UserData("jimmy", "123456");
75 Set<String> pets = new HashSet<String>();
76 pets.add("cat");
77 pets.add("dog");
78 Map<String, String> favoriteMovies = new HashMap<String, String>();
79 favoriteMovies.put("dragons", "Dragons II");
80 favoriteMovies.put("avator", "Avator I");
81 userData.setFavoriteMovies(favoriteMovies);
82 userData.setPets(pets);
83 userData.setBirthday(getDate(1990, 5, 1));
84 BasicDBObject objUser = new BasicDBObject("key", "jimmy").append(
85 "value", toDBObject(userData));
86 coll.insert(objUser);
87 System.out.println(coll.findOne(objUser));
88 }
89
90 /**
91 * 将普通Object对象转换成mongodb的DBObject对象
92 *
93 * @param obj
94 * @return
95 */
96 private DBObject toDBObject(Object obj) {
97 Gson gson = new Gson();
98 String json = gson.toJson(obj);
99 return (DBObject) JSON.parse(json);
100 }
101
102 /**
103 * 获取指定日期
104 *
105 * @param year
106 * @param month
107 * @param day
108 * @return
109 */
110 private Date getDate(int year, int month, int day) {
111 Calendar calendar = Calendar.getInstance();
112 calendar.clear();
113 calendar.set(year, month - 1, day);
114 return calendar.getTime();
115
116 }
117
118 }
MongoDB Java API 操作示例
本文介绍如何使用 Java API 进行 MongoDB 的 CRUD 操作,并演示了连接数据库、集合管理、文档增删改查及索引创建等基本功能。
1012

被折叠的 条评论
为什么被折叠?



