配置文件:
spring-mongo.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<context:property-placeholder location="classpath:config.properties" />
<!--replicaSetMongo 为配置多个mongos或 配置多个relicasetmongo,但是所配置的必须为同一类型 -->
<mongo:mongo id="replicaSetMongo" replica-set="${mongodb.host}">
<!-- 每个IP的连接数 -->
<mongo:options connections-per-host="100"
threads-allowed-to-block-for-connection-multiplier="50"
auto-connect-retry="true" />
</mongo:mongo>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="replicaSetMongo" />
<!--mongo的数据库名称 -->
<constructor-arg name="databaseName" value="${mongodb.dataname}" />
</bean>
</beans>
config.properties
#如果是集群的话可以用逗号分隔地址:192.168.1.123:27017,192.168.1.124:27017
mongodb.host=127.0.0.1:27017
mongodb.dataname=test
java类中使用
org.springframework.data.mongodb.core.MongoTemplate类做增删改查操作
常用 MongoTemplate API
增加方法:
// 增加一个
insert();
// 增加多个(批量)
insertAll();
删除:
// 删除
remove();
修改:
// 修改一个
updateFirst();
// 修改多个
updateMulti();
查询:
// 查找一个
findOne();
// 查找多个
find();
Criteria类
相等查询:Criteria.where().is();
大于:Criteria.where().gte();
存在(正则):Criteria.where().regex();
Query类
添加查询条件:query.addCriteria();
分页:query.skip();query.limit();
排序:query.with(new Sort(new Sort.Order(Sort.Direction.DESC,"属性名")));
Update类
update.set("属性名","属性值");
Query类常用查询