Using MongoDB summary in Spring MVC

Source: Internet
Author: User
Tags mongodb object model

Recent projects have been restructured to use Mysql+geohash to store lbs data (location information) and now use the NoSQL database MongoDB to store lbs data (location information). Since the project was developed based on Spring MVC, today's summary of the use of MongoDB is made. Spring MVC Integration MongoDB

1. Load Jar,maven Configuration

        <!--new Spring consolidation MongoDB package start--> <dependency> <groupid>org.mongodb</grou Pid> <artifactId>mongo-java-driver</artifactId> <version>2.13.0-rc0</versi on> </dependency> <dependency> <groupid>org.springframework.data</gro Upid> <artifactId>spring-data-mongodb</artifactId> <version>1.7.1.RELEASE< /version> </dependency> <dependency> <groupid>org.springframework.data&lt ;/groupid> <artifactId>spring-data-mongodb-cross-store</artifactId> <version> 1.7.1.release</version> </dependency> <dependency> <groupid>org.spring Framework.data</groupid> <artifactId>spring-data-mongodb-log4j</artifactId> < Version>1.7.1.release</version> </dependency> <!--The newly added spring consolidation MongoDB Package End--> 

2. Configure
MongoDB is integrated into 2 methods, namely stand-alone and cluster.
stand-alone configuration
Applicationcontext.xml

<mongo:mongo id= "MONGO" host= "${mongo.host}" port= "${mongo.port}" >
        <mongo:options Connections-per-host= "${mongo.connectionsperhost}" 
            threads-allowed-to-block-for-connection-multiplier= "${ Mongo.threadsallowedtoblockforconnectionmultiplier} " 
            connect-timeout=" ${mongo.connecttimeout} " Max-wait-time= "${mongo.maxwaittime}" 
            auto-connect-retry= "${mongo.autoconnectretry}" socket-keep-alive= "${" Mongo.socketkeepalive} " 
            socket-timeout=" ${mongo.sockettimeout} "slave-ok=" ${mongo.slaveok} "write-number=" 1 " 
            write-timeout= "0" write-fsync= "true"/> 
    </mongo:mongo>

Configuration file Common-config.properties

Mongo.dbname = test_db #数据库名称
mongo.password = test_pwd #密码
mongo.username = Test_user #用户名
mongo.host = 127. 0.0.1 #主机
mongo.port= 27017 #端口号
mongo.connectionsperhost= 8 #一个线程变为可用的最大阻塞数
Mongo.threadsallowedtoblockforconnectionmultiplier= 4 #线程队列数, which is the result of multiplying the Connectionsperhost value above the thread queue maximum value
mongo.connecttimeout= 1500 #连接超时时间 (milliseconds)
mongo.maxwaittime= 1500 #最大等待时间
mongo.autoconnectretry= true #自动重连
mongo.socketkeepalive= true #scoket保持活动
mongo.sockettimeout=1500 #scoket超时时间
mongo.slaveok=true # Read and write separation

Cluster Configuration
Applicationcontext.xml

<mongo:mongo  id= "MONGO"  replica-set= "${mongo.replicaset}" >
        <mongo:options Connections-per-host= "${mongo.connectionsperhost}"
            threads-allowed-to-block-for-connection-multiplier= "${ Mongo.threadsallowedtoblockforconnectionmultiplier} "
            connect-timeout=" ${mongo.connecttimeout} " Max-wait-time= "${mongo.maxwaittime}" auto-connect-retry= "${mongo.autoconnectretry}"
            socket-keep-alive= "${" mongo.socketkeepalive} "socket-timeout=" ${mongo.sockettimeout} "slave-ok=" ${mongo.slaveok} "
            write-number=" ${ Mongo.writenumber} "write-fsync=" ${mongodb.writefsync} "/>
    </mongo:mongo>

Configuration file Common-config.properties

Mongo.dbname = test_db
mongo.username = test_user Mongo.password = test_pwd mongo.replicaset
= 192.168.2.193:27017,192.168.2.192:27017
mongo.connectionsperhost=
Mongo.threadsallowedtoblockforconnectionmultiplier=50
mongo.connecttimeout=3000
mongo.maxWaitTime=5000
mongo.autoconnectretry=true
mongo.socketkeepalive=true
mongo.sockettimeout=5000
Mongo.slaveok=true
mongo.writenumber = 1
Mongodb.writefsync = True

Other Configuration

<!--user authentication--> <bean id= "usercredentials" class= "Org.springframework.data.authentication.UserCredentials" > <constructor-arg name= "username" value= "${mongo.username}"/> <constructor-arg name= "Passwor" D "value=" ${mongo.password} "/> </bean> <!--MONGO Factory, through which to obtain MONGO instance, dbname the database name of MongoDB, no words will be automatically created-
        > <bean id= "mongodbfactory" class= "Org.springframework.data.mongodb.core.SimpleMongoDbFactory" > <constructor-arg ref= "Mongo"/> <constructor-arg value= "${mongo.dbname}"/> <constructor -arg ref= "Usercredentials"/> </bean> <bean id= "Mappingcontext" class= Ta.mongodb.core.mapping.MongoMappingContext "/> <bean id=" Defaultmongotypemapper "class=" Org.springfram Ework.data.mongodb.core.convert.DefaultMongoTypeMapper "> <constructor-arg name=" Typekey "> ; null/> </consTructor-arg> </bean> <!--collection mapping--> <bean id= "Mappingmongoconverter" class= "Org.springframework.data.mongodb.core.convert.MappingMongoConverter" > <constructor-arg name= "
        Mongodbfactory "ref=" mongodbfactory "/> <constructor-arg name=" Mappingcontext "ref=" MappingContext "/> <property name= "Typemapper" ref= "Defaultmongotypemapper"/> </bean> <!--MongoDB's main operational objects, all of the Ongodb of the deletion and modification of the operation are through it to complete--> <bean id= "mongotemplate" class= " Org.springframework.data.mongodb.core.MongoTemplate "> <constructor-arg name=" mongodbfactory "ref=" MONGODBFA Ctory "/> <constructor-arg name= mongoconverter" ref= "Mappingmongoconverter"/> </bean>
MongoDB additions and deletions to change the investigation

1.Mongodb Object Model
Dynamic.java

@Document (collection = "dynamic") public
class Dynamic implements serializable{

    /**
     * * *
    Private Static final Long serialversionuid = 179822189115264434L;
    Private String _id; 
    Private String userId;     User ID    
    Private date releasedate;//publication date 
    private double []loc = new double[2];//position public

    void SetId (String _id) {
        this._id = _id;
    }

    Public String GetId () {return
        this._id;
    }

    Public String GetUserID () {return
        userId;
    }
    public void Setuserid (String userId) {
        This.userid = userId;
    }
    Public Date Getreleasedate () {return
        releasedate;
    }
    public void Setreleasedate (Date releasedate) {
        this.releasedate = releasedate;
    }
    Public double[] Getloc () {return
        loc;
    }
    public void Setloc (double[] loc) {
        this.loc = loc;
    }



}

2. code example
New

Dynamic dynamic = New dynamic ();
Dynamic.setuserid ("10023");
// ...
Set property, self complement
//convert to DBObject
dbobject dbobject = beanutil.bean2dbobject (dynamic);
        Db.removefield ("Serialversionuid");
Save
Mongotemplate.getcollection (collection). Save (DBObject)

Update
General Update

DBObject aim = new Basicdbobject ("_id", id);
DBObject setValue = new Basicdbobject ();
Setvalue.put ("Loc", Loc.getloc ());
Updated values, with $set
dbobject updatesetvalue = new Basicdbobject ("$set", setValue);

Update, Aim:where condition Updatesetvalue: Update value true: Insert False if no record: multiple-row update
mongotemplate.getcollection (collection). Update (AIM, Updatesetvalue, True,
                false);

Array update

DBObject Addaim = new Basicdbobject ();
        Addaim.put ("_id", id);
The push value in the data
is dbobject updatesetvalue = new Basicdbobject ("$push", addedvalue);
Add
updatesetvalue.put ("$inc", New Basicdbobject ("Commentsize", 1));
Mongotemplate.getcollection (collection). Update (Addaim, updatesetvalue);

Query
Single Query

DBObject query = new Basicdbobject ("_id", id);
DBObject fields = new Basicdbobject ();
Mongotemplate.getcollection (collection). FindOne (query, fields)

Page-Search

int pageSize =;
int pagenum = 1;
DBObject fields = new Basicdbobject ();
Sort,-1 descending
dbobject by = new Basicdbobject ("Release_date",-1);

Paging query
list<dbobject> List = new arraylist<> ();
Cursor Cursor = Mongotemplate.getcollection (collection). Find
        (query, fields). Skip ((pageNum-1) * pageSize)
        . Limit (pageSize). sort (by);
while (Cursor.hasnext ()) {
    List.add (Cursor.next ());
}       

Scope Query

DBObject query = new Basicdbobject ();
$lte is less than or equal, $lt less than
query.put (
        "Release_date",
        new Basicdbobject ("$lte", Dateutil.parsedate (
                MaxTime, Datestyle.yyyy_mm_dd_hh_mm_ss_sss
                        . GetValue ()));
$gte greater than or equal, $gt greater than
query.put (
        "Release_date",
        new Basicdbobject ("$gte", Dateutil.parsedate (
                Mintime, Datestyle.yyyy_mm_dd_hh_mm_ss_sss
                        . GetValue ()));

In and not in query

$in queries
dbobject query = new Basicdbobject ("qd_id", New Basicdbobject (
                    "$in", Idstr))
//$nin query
Dbobje CT query = new Basicdbobject ("qd_id", New Basicdbobject (
                    "$nin", Idstr)

or query

List Orarry = new arraylist<> ();
                Orarry.add (New Basicdbobject ("qd_id", New Basicdbobject (
                        "$in", Qd_ids.toarray ()));
                Orarry.add (New Basicdbobject ("_id", New Basicdbobject ("$in", Recommondids.toarray ()));
                Query.put ("$or", Orarry);

Aggregate query sum and GROUP by

Map Retmap = new hashmap<> (); $group groupings, Newscount aliases, $sum and, $commentSize field names String groupstr = "{$group: {_id:null,newscount:{$sum: 1},commentcoun
        t:{$sum: \ "$commentSize \"},supportcount:{$sum: \ $supportSize \ "}}}";
        DBObject Group = (dbobject) json.parse (GROUPSTR);
        String mintime = (string) params.get ("start") + "00:00:00:000";
        String maxtime = (string) params.get ("End") + "00:00:00:000";
        Basicdbobject query = new Basicdbobject ();
                        Query.put ("Release_date", New Basicdbobject ("$gte", Dateutil.parsedate (
        Mintime, Datestyle.yyyy_mm_dd_hh_mm_ss_sss. GetValue ()));
                        Query.put ("Release_date", New Basicdbobject ("$lte", Dateutil.parsedate (
                        MaxTime, Datestyle.yyyy_mm_dd_hh_mm_ss_sss. GetValue ()). Append ("$gte",
   Dateutil.parsedate (Mintime,                             Datestyle.yyyy_mm_dd_hh_mm_ss_sss. GetValue ()));
DBObject match = new Basicdbobject ("$match", query);
        Aggregate query Aggregationoutput output = Mongotemplate.getcollection (collection). Aggregate (Match,group); For (iterator< dbobject > it = Output.results (). iterator (); It.hasnext ();)
            {basicdbobject dbo = (basicdbobject) it.next ();
        Retmap = Com.alibaba.fastjson.JSON.parseObject (dbo.tostring (), map.class); return retmap;

lbs Query (people in the vicinity)

if (query = = NULL)
            query = new Basicdbobject ();

list<dbobject> pipeLine = new arraylist<> ();
Basicdbobject pipebasicdbobject = new Basicdbobject ();

Pipebasicdbobject.append ("Near", new double[] {longitude, latitude})
. Append ("Distancefield", "dist.calculated"
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.