我是靠谱客的博主 清秀微笑,这篇文章主要介绍详解MongoDB数据库基础操作及实例,现在分享给大家,希望可以做个参考。

详解数据库基础操作及实例

          废话不多说,直接上代码,注释写的比较清楚,大家参考下,

 示例代码:

复制代码
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
/** * 插入一条DB对象 */ public static void addDBObject(DBCollection collection,BasicDBObject object){ collection.insert(object); } /** * 根据id查询DBObject */ public static DBObject getDBObjectById(String value) throws UnknownHostException, MongoException{ dbc = getDBCollection("company", "users").find(new BasicDBObject("_id",new ObjectId(value))); DBObject ob = null; int i = 0; while(dbc.hasNext()){ ob = dbc.next(); i++; } if(i == 1){ return ob; }else{ return null; } } /** * 根据key和value值查询 */ public static DBObject getDBObject(String key,String value) throws UnknownHostException, MongoException{ dbc = getDBCollection("company", "users").find(new BasicDBObject(key,value)); DBObject ob = null; int i = 0; while(dbc.hasNext()){ ob = dbc.next(); i++; } if(i == 1){ return ob; }else{ return null; } } /** * 根据数据库名获取(新增)下面所有聚集名(表名) */ public static Set<String> getCollectionsNames(String DBName) throws MongoException, UnknownHostException{ return getDB(DBName).getCollectionNames(); } /** * 遍历聚集中的db对象集合(相当于关系数据库中的数据) */ public static Set<DBObject> getDBObjects(DBCollection collection){ Set<DBObject> dbObjects = new HashSet<DBObject>(); DBCursor cursor = collection.find(); while(cursor.hasNext()){ DBObject object = cursor.next(); dbObjects.add(object); } return dbObjects; } /** * 获取/新增聚集(相当于关系数据库表) */ public static DBCollection getDBCollection(String DBName,String collectionName) throws UnknownHostException, MongoException{ return getDB(DBName).getCollection(collectionName); } /** * 获取/新增数据库 */ public static DB getDB(String DBName) throws UnknownHostException, MongoException{ return getMongo().getDB(DBName); } /** * 连接数据库 */ public static Mongo getMongo() throws UnknownHostException, MongoException{ Mongo mg = null; if(mg == null){ mg = new Mongo(); } return mg; } /** * 关闭连接 */ public static void destory(Mongo mg) { if (mg != null){ mg.close(); mg = null; } System.gc(); } /** * 获取数据库名 */ public static List<String> getDBNames() throws MongoException, UnknownHostException{ return getMongo().getDatabaseNames(); } /** * 删除数据库 */ public static void deleteDB(String DBName) throws MongoException, UnknownHostException{ getMongo().dropDatabase(DBName); }

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

最后

以上就是清秀微笑最近收集整理的关于详解MongoDB数据库基础操作及实例的全部内容,更多相关详解MongoDB数据库基础操作及实例内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(113)

评论列表共有 0 条评论

立即
投稿
返回
顶部