当前位置: 移动技术网 > IT编程>开发语言>Java > Mongodb使用

Mongodb使用

2019年01月08日  | 移动技术网IT编程  | 我要评论

本文主要介绍mongodb在java应用中如何进行增、删、查、改操作。

一、配置

1、将 common.jar库引入到项目环境中: (源代码:,可直接下载lib目录下的jar文件使用) 

  如果是maven项目,可以通过mvn install命令将common.jar加入到本地仓库:

mvn install:install-file -dfile=d:\lib\common-1.0.jar -dgroupid=com.cnsugar -dartifactid=common -dversion=1.0 -dpackaging=jar

然后在pom.xml中加入以下配置:

<dependency>
    <groupid>com.cnsugar</groupid>
    <artifactid>common</artifactid>
    <version>1.0</version>
</dependency>

  

  也可以直接将jar文件放到项目中,用下面的方式引入:

<dependency>
<groupid>com.cnsugar</groupid>
<artifactid>common</artifactid>
<version>1.0</version>
<scope>system</scope>
<systempath>${project.basedir}/lib/common-1.0.jar</systempath>
</dependency>

 

2、用同样的方式将 common-mongodb.jar库引入到项目环境中: (源代码:,可直接下载lib目录下的jar文件使用) 

3、增加依赖包  

    <properties>
        <fastjson-version>1.2.23</fastjson-version>
        <spring.version>4.2.8.release</spring.version>
        <spring.mongodb-version>1.9.5.release</spring.mongodb-version>
        <mongo-version>3.3.0</mongo-version>
    </properties>

    <dependencies>
        <dependency>
            <groupid>com.alibaba</groupid>
            <artifactid>fastjson</artifactid>
            <version>${fastjson-version}</version>
        </dependency>

        <dependency>
            <groupid>org.springframework</groupid>
            <artifactid>spring-jdbc</artifactid>
            <version>${spring.version}</version>
        </dependency>
        <!-- mongo -->
        <dependency>
            <groupid>org.springframework.data</groupid>
            <artifactid>spring-data-mongodb</artifactid>
            <version>${spring.mongodb-version}</version>
            <exclusions>
                <exclusion>
                    <groupid>org.springframework</groupid>
                    <artifactid>*</artifactid>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupid>org.mongodb</groupid>
            <artifactid>mongo-java-driver</artifactid>
            <version>${mongo-version}</version>
        </dependency>
    </dependencies>

 

 

4、增加spring配置文件

  mongodb-config.properties

#集群模式
#mongodb.hosts=10.10.10.239:20000,10.10.10.224:20000,10.10.10.238:20000

#单机模式 mongodb.host=192.168.241.34 mongodb.port=27017

#数据库名称 mongodb.dataname=datagateway

 

 

  spring-context-config.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"
       xsi:schemalocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
          
    <bean id="propertyconfigurer" class="org.springframework.beans.factory.config.propertyplaceholderconfigurer">
        <property name="locations">
            <list>
                <value>classpath:mongodb-config.properties</value>
            </list>
        </property>
    </bean>
</beans>

 

  如果需要在项目中读取其他配置文件中的内容,可以将org.springframework.beans.factory.config.propertyplaceholderconfigurer 换成 com.cnsugar.common.config.systemconfig,可以直接使用systemconfig中的静态get方法读取配置文件。

  

  spring-context-mongodb.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">
    <mongo:mongo-client id="mongo" 
        host="${mongodb.host}"
        port="${mongodb.port}">
        <mongo:client-options connections-per-host="10"
            threads-allowed-to-block-for-connection-multiplier="5"
            connect-timeout="30000" 
            socket-timeout="60000" 
            write-concern="safe" />
    </mongo:mongo-client>
    <bean id="mongosupport" class="com.cnsugar.common.mongodb.mongosupport">
        <constructor-arg name="mongo" ref="mongo" />
        <constructor-arg name="dbname" value="${mongodb.dataname}" />
    </bean>
</beans>  
  mongo-client配置属性说明:
    id: mongoclient的名称,默认值:mongoclient
    port: 连到到mongodb服务器的端口号,默认:27017
    host: 连接到mongodb服务器的host,默认:localhost
    replica-set: 逗号分隔的的副本集集合,格式为host:port,host:port
    credentials: 用户身份认证逗号分隔的配置,格式:username:password@database,如果传递的认证包含逗号,则使用单引号括起来
client-options配置属性说明:
        description: 描述
        min-connections-per-host: 客户端最小连接数
        connections-per-host: 客户端最大连接数,超过了将会被阻塞,默认100
        threads-allowed-to-block-for-connection-multiplier: 可被阻塞的线程数因子,默认值为5,如果connectionsperhost配置为10,那么最多能阻塞50个线程,超过50个之后就会收到一个异常
        max-wait-time: 阻塞线程获取连接的最长等待时间,默认120000 ms
        max-connection-idle-time: 连接池连接最大空闲时间
        max-connection-life-time: 连接池连接的最大存活时间
        connect-timeout: 连接超时时间,默认值是0,就是不超时
        socket-timeout: socket超时时间,默认值是0,就是不超时
        socket-keep-alive: keep alive标志,默认false
      server-selection-timeout: 服务器查询超时时间,它定义驱动在抛出异常之前等待服务器查询成功,默认30s,单位milliseconds
        read-preference: mongodb有5种readpreference模式:
            primary    主节点,默认模式,读操作只在主节点,如果主节点不可用,报错或者抛出异常。
            primarypreferred   首选主节点,大多情况下读操作在主节点,如果主节点不可用,如故障转移,读操作在从节点。
            secondary    从节点,读操作只在从节点, 如果从节点不可用,报错或者抛出异常。
            secondarypreferred    首选从节点,大多情况下读操作在从节点,特殊情况(如单主节点架构)读操作在主节点。
            nearest    最邻近节点,读操作在最邻近的成员,可能是主节点或者从节点。
        write-concern: writeconcern的7种写入安全机制抛出异常的级别:
            none: 没有异常抛出
            normal: 仅抛出网络错误异常,没有服务器错误异常,写入到网络就返回。
            safe: 抛出网络错误异常、服务器错误异常;并等待服务器完成写操作。
            majority: 抛出网络错误异常、服务器错误异常;并多数主服务器完成写操作。
            fsync_safe: 抛出网络错误异常、服务器错误异常;写操作等待服务器将数据刷新到磁盘。
            journal_safe: 抛出网络错误异常、服务器错误异常;写操作等待服务器提交到磁盘的日志文件。
            replicas_safe: 抛出网络错误异常、服务器错误异常;等待至少2台服务器完成写操作。
        heartbeat-frequency: 驱动用来确保集群中服务器状态的心跳频率
        min-heartbeat-frequency: 驱动重新检查服务器状态最少等待时间
        heartbeat-connect-timeout: 集群心跳连接的超时时间
        heartbeat-socket-timeout: 集群心跳连接的socket超时时间
        ssl: 驱动是否使用ssl进行连接,默认是false
        ssl-socket-factory-ref: 用来进行ssl连接的sslsocketfactory,如果配置为none,则使用sslsocketfactory.getdefault()
  

二、使用示例

   测试之前先新建一个实体类testentity,增加@collection注解指明对应mongodb中test表。mongodb在新增数据时会自动生成一个主键_id,如果要以_id为条件进行操作需要转成objectid对象才能使用,继承mongoentity可以调用getobjectid()自动处理。

  如果要控制字段的顺序,可在字段上添加@jsonfield注解,用ordinal属性进行控制。如果表中的字段名与实体中的字段名不一致,可以添加name属性进行设置(如下面的代码,实体中testscore字段对应的数据库中的名字为test_score)。

@collection("test")
public class testentity extends mongoentity {
    @jsonfield(ordinal = 2)
    private string name;

    @jsonfield(ordinal = 3)
    private int status; 

    @jsonfield(name="test_score", ordinal = 4)
    private float testscore;

private date ontime = new date(); @jsonfield(serialize = false) private string msgid;//不需要保存到数据库中的字段,serialize设为false //setter、getter方法 }

 

  1、新增示例

  使用save方法进行新增数据,批量新增用saveall方法。

  @org.junit.test
    public void testsave() {
        //保存实体对象
        testentity entity = new testentity();
        entity.setname("sugar");
        entity.setstatus(2);
        entity.settestscore(97.5f);
        mongoutils.save(entity);

        //保存map对象,需要指定集合名称
        map<string, object> map = new hashmap<>();
        map.put("name", "zhangshan");
        map.put("status", 2);
        map.put("test_score", 97.5f);
        mongoutils.save(map, "test");

        //保存document对象,与map类似,需要指定集合名称
        document doc = new document();
        doc.put("name", "lisi");
        doc.put("status", 2);
        doc.put("test_score", 97.5f);
        mongoutils.save(doc, "test");
    }

   使用robomongo客户端查看执行后的结果如下:

   

 

  2、更新

  调用update开头的方法进行更新操作,更新条件使用filters对象设置,更新内容使用update对象设置;批量更新用updateall方法。

  @org.junit.test
    public void testupdate() {
        //更新java对象,必须要指定id,如果字段值为null,不会更新旧的数据
        testentity entity = new testentity();
        entity.setid("5c343804fdfad4230852e1f5");
        entity.setname("sugar2");
        entity.setstatus(1);
        mongoutils.update(entity);

        //自定义更新的集合名、条件、字段
        string collectionname = "test";
        bson filter = filters.eq("_id", new objectid("5c343804fdfad4230852e1f6"));
        update update = new update();
        update.set("name", "zhangshan2");
        update.inc("status", 1);//相当于status += 1
        mongoutils.update(collectionname, filter, update);
    }

   更新后的结果如下图:

  

  

  3、查询

  调用find开头的方法进行查询,查询条件使用filters对象设置;分页查询用findpage。

    @org.junit.test
    public void testquery() {
        //查询出实体列表
        list<testentity> ll = mongoutils.findall(testentity.class);
        system.out.println(ll);

        //查询document对象列表,需要指定集合名
        list<document> list = mongoutils.findall("test");
        system.out.println(list);

        //用filters生成条件查询,查询名字以2结尾的数据
        list<testentity> ll2 = mongoutils.find(testentity.class, filters.regex("name", ".*2"));
        system.out.println(ll2);

        //分页查询,查询分数大于90的数据,查询第1页,每页10条
        page page = new page(10, 1);
        page.setclazz(testentity.class);//指定列表中的对象类型
        page = mongoutils.findpage(page, filters.gt("test_score", 90));
        system.out.println(page.getlist());
    }

 

 

  4、删除

  调用delete开头的方法进行删除操作,条件使用filters对象设置

  @org.junit.test
    public void testdelete() {
        //根据id删除
        mongoutils.deletebyid("test", "587482defdfad41a9c94c9b6");

        //删除一条数据
        mongoutils.deleteone("test", filters.eq("_id", new objectid("587482defdfad41a9c94c9b6")));

        //批量删除
        list<objectid> del = new arraylist<objectid>();
        del.add(new objectid("587482defdfad41a9c94c9b6"));
        del.add(new objectid("58748350fdfad41a1c5fba14"));
        del.add(new objectid("5874930ffdfad40df031215a"));
        mongoutils.deleteall("test", filters.in("_id", del));
    }

 

 

  5、数据聚合分析

  使用count或mapreduce进行数据聚合分析;

  @org.junit.test
    public void testcount() {
        //统计test表数据总数
        long count = mongoutils.count("test");

        //统计test表中status=2的数据总数
        long count2 = mongoutils.count("test", filters.eq("status", 2));
        
        //根据status进行分组统计
        list<document> list = mongoutils.count("test", new string[]{"status"});
        system.out.println(list);

        //自定义mapreduce函数进行数据分析,按天统计数据总数和status=1的总数
        stringbuilder mapfunction = new stringbuilder("function(){emit(");
        mapfunction.append("new date(this.ontime).tolocaledatestring()");
        mapfunction.append(",{count:1, send:this.status==1?1:0}");
        mapfunction.append(");}");
        stringbuilder reducefunction = new stringbuilder("function(key, values){");
        reducefunction.append("var _total = 0, _send = 0;");
        reducefunction.append("values.foreach(function(val){_total += val.count; _send += val.send;});");
        reducefunction.append("return {count:_total, send:_send};");
        reducefunction.append("}");
        list<document> list2 = mongoutils.mapreduce("test", mapfunction.tostring(), reducefunction.tostring());
        system.out.println(list2);
    }

 

 

  更多使用方法请参考:

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网