mongo operation

一、驱动

mongo对应的java驱动的下载地址

https://github.com/mongodb/mongo-java-driver/downloads

 

二、文档

API文档的地址

http://api.mongodb.org/java/

官方入门地址

http://www.mongodb.org/display/DOCS/Java+Tutorial

 

三、官方的几点说明(未完全翻译官方网站提供的所有内容)

1.java驱动的并发情况

    mongo db的java驱动是线程安全的,在一个web项目中,可以创建一个Mongo的单例,然后在每次请求时都使用这个单例。该单例会维护一个内部的连接池(默认大小为10),对于每次对DB的请求(find、insert等),java线程都会从连接池中获取一个连接,进行操作,然后释放连接,所以,每次使用的连接可能不总是同一个连接。如果你想一直使用同一个连接,可以用下边这种方式:


DB db...;
db.requestStart();
code....
db.requestDone();


    但是如果最后db.requestDone()没有被调用,该连接不会被交还给线程池,所以,一定要在finally块中调用db.requestDone()。

    DB和DBCollection都是线程安全的。

    在默认配置的情况下,每次对DB请求(find、insert等)后,连接会被交还给连接池,你并不知道是否操作成功,这会造成“数据无故丢失”的情况。所以,对于数据安全性比较重要的操作,我们要使用WriteConcern.SAFE模式,这样,驱动会在将连接交还前调用getLastError()方法来校验是否操作成功。示例如下:

DBCollection coll...;
coll.insert(..., WriteConcern.SAFE);

2.数据类型

 

 

(1)正则表达式

    java驱动使用java.util.regex.Pattern做正则表达式:

 

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);

 

(2)日期、时间

    java驱动使用java.util.Date做日期:

 

Date now = new Date();
BasicDBObject time = new BasicDBObject("ts", now);
collection.save(time);

 

(3)内嵌文档

 

{
    "x" : {
        "y" : 3
    }
}

 

上边这种文档结构可以用下边这种方式存储

 

BasicDBObject y = new BasicDBObject("y", 3);
BasicDBObject x = new BasicDBObject("x", y);

 

(4)数组

    扩展自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);

四、MongoOptions

 

java驱动中,可以在获取mongo实例时,指定一些参数,如下:

ServerAddress serverAddress=new ServerAddress("127.0.0.1",27017);

 

MongoOptions mongoOptions=new MongoOptions();

Mongo mongo=new Mongo(serverAddress,mongoOptions);

参数列表如下:

 

#控制系统在发生连接错误时是否重试 ,默认为false --boolean

mongo.options.autoConnectRetry=false

#每个主机允许的连接数(每个主机的连接池大小),当连接池被用光时,会被阻塞住 ,默认为10 --int

mongo.options.connectionsPerHost=10

#multiplier for connectionsPerHost for # of threads that can block if connectionsPerHost is 10, and threadsAllowedToBlockForConnectionMultiplier is 5, then 50 threads can block more than that and an exception will be throw --int

mongo.options.threadsAllowedToBlockForConnectionMultiplier=5

#被阻塞线程从连接池获取连接的最长等待时间(ms) --int

mongo.options.maxWaitTime 

#在建立(打开)套接字连接时的超时时间(ms),默认为0(无限) --int

mongo.options.connectTimeout=0

#套接字超时时间;该值会被传递给Socket.setSoTimeout(int)。默认为0(无限) --int

mongo.options.socketTimeout=0

#This controls whether or not to have socket keep alive turned on (SO_KEEPALIVE). defaults to false --boolean

mongo.options.socketKeepAlive=false

#Override the DBCallback factory. Default is for the standard Mongo Java driver configuration --DBCallbackFactory

mongo.options.dbCallbackFactory 

#//指明是否允许驱动从次要节点或者奴隶节点读取数据,默认为false --boolean

mongo.options.slaveOk=false

#如果为true,驱动每次update后会发出一个getLastError命令来保证成功,默认为false --boolean

mongo.options.safe=false 

#If set, the w value of WriteConcern for the connection is set to this. Defaults to 0; implies safe = true --int

mongo.options.w=0

#If set, the wtimeout value of WriteConcern for the connection is set to this. Defaults to 0; implies safe = true --int

mongo.options.wtimeout=0

#Sets the fsync value of WriteConcern for the connection. Defaults to false; implies safe = true --boolean

mongo.options.fsync=false

 

五、杂

ObjectId由4部分编码而成:当前时间、机器标识、进程号和自增的整数。

排序加翻页

collection.find(queryObject).sort(new BasicDBObject().append("pt", "-1").append("ct", "1")).skip(10).limit(10);

 

 

 

 

 

小记录:

从名为tag的数组中删除值为123的元素

BasicDBObject updateObject = new BasicDBObject().append("$pull", new BasicDBObject().append("tag","123"));

//queryObject是查询条件

dbCollection.updateMulti(queryObject, updateObject);

 

 

 

 

 

 

MongoTemplate 是 Spring Data MongoDB 提供的一个操作 MongoDB 的模板类。它提供了一系列的方法,可以方便地进行数据库的增删改查操作。 要在 MongoTemplate 中进行分组操作,可以使用 `group` 方法。`group` 方法接受一个 `GroupOperation` 对象作为参数,用于定义分组的条件和操作。 以下是一个简单的示例代码,展示了如何在 MongoTemplate 中进行分组操作: ```java import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.GroupOperation; import org.springframework.data.mongodb.core.aggregation.TypedAggregation; import org.springframework.data.mongodb.core.query.Criteria; ... // 创建分组操作 GroupOperation groupOperation = Aggregation.group("category").count().as("count"); // 创建聚合操作 TypedAggregation aggregation = Aggregation.newAggregation( Aggregation.match(Criteria.where("price").gt(100)), // 添加筛选条件 groupOperation ); // 执行聚合操作 List<AggregationResults<GroupResult>> results = mongoTemplate.aggregate(aggregation, "collectionName", GroupResult.class).getMappedResults(); // 遍历结果 for (AggregationResults<GroupResult> result : results) { GroupResult groupResult = result.getUniqueMappedResult(); String category = groupResult.get_id(); Long count = groupResult.getCount(); // 处理分组结果 } ``` 上述代码中,首先创建了一个 `GroupOperation` 对象,指定了要按照 "category" 字段进行分组,并使用 `count` 方法进行计数。 然后,创建了一个 `TypedAggregation` 对象,通过 `Aggregation.match` 方法添加了一个筛选条件,只选择 "price" 大于 100 的文档。接着将之前创建的 `GroupOperation` 对象添加到聚合操作中。 最后,使用 `mongoTemplate.aggregate` 方法执行聚合操作,并通过 `getMappedResults` 方法获取结果。 请注意,上述代码中的 "collectionName" 需要替换为实际的集合名称,"GroupResult" 是一个自定义的结果类,用于接收分组结果。 希望对你有所帮助!如果你还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值