现在的位置: 首页 > 综合 > 正文

MongoDb学习

2018年04月02日 ⁄ 综合 ⁄ 共 4841字 ⁄ 字号 评论关闭

下周起,有个小项目中要使用MogoDb来进行存储,选用它,考虑到其面向对象存储,且业界表现不俗的口碑。另外一个为了以后更大的项目能应用,也算一点技术积累吧。

周末无事,在官网文档的帮忙下,边看边写了一些测试用例,简单使用后,算是懂得如何使用了。

官网上相关资料进行了简单的记录,对入门算是有个简单的帮忙:

一.下载与安装

下载地址:http://www.mongodb.org/downloads

win下:
解压bin目录下所有exe文件到一个目录,比如c:\mongodb
在此目录下新建data目录,
这样在命令行执行
mongod.exe --dbpath c:\mongdb\data 
即可启动mongodb了,数据保存在上面指定的data目录下
mongodb 不同语言驱动下载地址:
二.基本使用
2.1 MongoClient说明
1.MongoClient 线程安全
2.如果多个MongoClient实例,需要注意:配制每个实例的usage
limits(max connections) , 另外需要释放实例时,需要
MongoClient.close.
3.可以认证:
MongoClient提供了认证的功能:
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("test");
boolean auth = db.authenticate(myUserName, myPassword);
大部分情况不用auth.

2.2 获取集合列表:
getting a list of collections
Set<String> colls = db.getCollectionNames();

for (String s : colls) {
    System.out.println(s);
}


获取collection
getCollection(String collectionName);
DBCollection coll = db.getCollection("testCollection");
Once you have this collection object, you can now do things like insert data, query for data, etc

2.3 设置mongodb写(有很多种方式)
2.10.0之前默认为
mongoClient.setWriteConcern(WriteConcern.JOURNALED);
Write operations that use this write concern will return as soon as the message is written to the socket. Exceptions are raised for network issues, but not server errors.
This field has been superseded by WriteConcern.UNACKNOWLEDGED, and may be deprecated in a future release
2.10.0以后改写为
WriteConcern.ACKNOWLEDGED:
Write operations that use this write concern will wait for acknowledgement from the primary server before returning. Exceptions are raised for network issues, and server errors.

2.4 mongodb插入document
insert a document
a json object 如下:
a json
{
   "name" : "MongoDB",
   "type" : "database",
   "count" : 1,
   "info" : {
               x : 203,
               y : 102
             }
}
使用BaseDBObject
BasicDBObject doc = new BasicDBObject("name", "MongoDB").
                              append("type", "database").
                              append("count", 1).
                              append("info", new BasicDBObject("x", 203).append("y", 102));
coll.insert(doc);

注意:
insert 插入相同的元素时会报错。
还对于save方法,则会更新此元素。

mongodb查找document
简单使用findOne(),得到collection第一个document.
find() 方法返回DBCursor 可查找找有的document.
每个object 插入时会自动增加_id对象。 另外mongodb保留的元素命名是以"_"/"$".内部使用。

2.5 使用DBCursor获取此collection的所有元素
DBCursor cursor = coll.find();
try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}
2.6 使用query方法查询一个document
BasicDBObject query = new BasicDBObject("i", 71);
cursor = coll.find(query)
try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

2.7 mongodb范围查询
经常看示例,DB查询使用“$”操作符,此操作符为范围查询,如下:
db.things.find({j: {$ne: 3}, k: {$gt: 10} });
内部是使用DBObjects:
BasicDBObject query = new BasicDBObject("j", new BasicDBObject("$ne", 3).
                                      append("k", new BasicDBObject("$gt", 10));
cursor = coll.find(query);
try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

使用query 获取documents 集合。
使用collection查询,如果想查询"i" > 50 可以如下:
query = new BasicDBObject("i", new BasicDBObject("$gt", 50));  // e.g. find all where i > 50
cursor = coll.find(query);
try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}
如果是20 < i <= 30,
query = new BasicDBObject("i", new BasicDBObject("$gt", 20).
                                               append("$lte", 30));  // i.e.   20 < i <= 30
三.Mongodb的管理功能
3.1 创建index
Mongodb支持索引,通过collection可以很容易增加,为了创建索引,只需要说明这个field应该indexed.
而且索引可以升序或者降序。
如下升序创建如下:
coll.createIndex(new BasicDBObject("i", 1));  // create index on "i", ascending

3.2 获取一个列表上的索引集合
List<DBObject> list = coll.getIndexInfo();
for (DBObject o : list) {
   System.out.println(o);
}

3.3 获取database集合
MongoClient mongoClient = new MongoClient();
for (String s : m.getDatabaseNames()) {
   System.out.println(s);
}

3.4 丢弃一个databases
MongoClient mongoClient = new MongoClient();
mongoClient.dropDatabase("myDatabase");

四.java 类型
(http://docs.mongodb.org/ecosystem/drivers/java-types/#java-types)
4.1 object Ids
com.mongodb.ObjectId 可以被用来创建唯一的ids.
ObjectId id = new ObjectId();
id.getInc();

4.2 支持正则表达式
Pattern john = Pattern.compile("joh?n", CASE_INSENSITIVE);
BasicDBObject query = new BasicDBObject("name", john);
// finds all people with "name" matching /joh?n/i
DBCursor cursor = collection.find(query);

4.3 dates/times
可以使用java.util.Date用做日期
Date now = new Date();
BasicDBObject time = new BasicDBObject("ts", now);
collection.save(time);

4.4 database引用。
com.mongodb.DBRef 能够用于保存数据库引用
简单了解后,使数据结构变得有些复杂了。(暂不发表观点)

4.5 Binary数据
byte[]会自动会被wrap成Binary类型,另外Binary类表示Binary Object-自定义的二进制类型

4.6 Timestamp data
时间戳在mongodb中是一个特别的对象,基于时间作为ID ,以pair表示(秒时间,自增长ID), 特别被用中同步的操作日志。 一个时间戳使用BSONTimestamp 类表示。

4.7 Code data
code object被用来表示 javascipt code,例如当执行system.js中的函数时,Code与CodeWScope 类可以被用来表示这些数据。

4.8 数组
java中任何对象继续List 将会被保存为数组。
如下:
{
    "x" : [
           1,
           2,
           {"foo" : "bar"},
           4
    ]
}
可以编码如下:
ArrayList x = new ArrayList();
x.add(1);
x.add(2);
x.add(new BasicDBObject("foo", "bar"));
x.add(4);
BasicDBObject doc = new BasicDBObject("x", x);
以上相关资料在官网都可以找到,如果OK的话,还是建议查看官网相关资料。
(mongodb 集群搭建:http://www.lanceyan.com/tech/mongodb/mongodb_cluster_1.html)

抱歉!评论已关闭.