Execute MongoDB under Java

Source: Internet
Author: User
Tags findone mongodb driver relational database table

1.1 Even single MongoDB

Mongo mg = newMongo ();//default 127.0.0.1 port is 27017

Mongo mg = newMongo (IP);//You can specify that the IP port defaults to 27017

Mongo mg = newMongo (ip,port);//can also specify IP and port number

1.2 Double-stage MongoDB

IP is the host IP address, port is the port number, DatabaseName corresponds to the database name

Dbaddress left = new Dbaddress ("Ip:port/databasename");

Dbaddress right = new Dbaddress ("Ip:port/databasename");

If there is a problem with MongoDB, it will automatically connect another one.

Mongo Mongo = new Mongo (left, right);

1.3 Even more than one MongoDB

list<serveraddress> mongohostlist = newarraylist<serveraddress> ();

Mongohostlist.add (newserveraddress ("IP", port));

Mongohostlist.add (newserveraddress ("IP", port));

Mongohostlist.add (newserveraddress ("IP", port));

Mongo mg = newMongo (mongohostlist);

2.1 Getting the db of MongoDB

DatabaseName equivalent to the database name in the relational database, MongoDB without the database name will not be error, the default MONGODB will establish this database name, is empty.

DB db = Mg.getdb (dataBaseName); Note: MongoDB is case-sensitive and must be noted in the program

DB Security Authentication for 2.2MONGODB

If you want to access the DB in collection (equivalent to the table in the relational database), you must pass security authentication to access, or the background will be reported that you did not pass security authentication.

Secure authentication Java code returns true for pass, false indicates failure to operate by

boolean auth =db.authenticate ("userName", "Password". ToCharArray ());

3.1 Getting the collection of the DB in MongoDB

Dbcollection users = db.getcollection (tableName);

The parameter tablename is equivalent to the table name in the relational database, and if there is no tablename in MongoDB, the TableName is created by default, which is an empty

Collection self-growing primary key for DB in 3.2mongodb

MongoDB is also like a traditional relational database table, with a primary key (_id) concept, to uniquely identify them. When a user inserts a new record into the collection,

If you do not specify the _id property, MongoDB automatically generates a value of type Objectid, saved as a value of _id.

3.3java insert operation on Collection

The first type of insertion method

DBObject data1 = newbasicdbobject ();

Data1.put ("cust_id", "123456");

Data1.put ("Is_show", 1);

Data1.put ("Start_time", newDate ());

Users.insert (data1);//equivalent to Users.save (DATA1);

The second Insert method

BasicDBObjectBuilderdata1 =basicdbobjectbuilder. Start (). Add (...). Add (...);

Users.insert (Data1.get ());//equivalent to Users.save (Data1.get ());

The third method of insertion

map<string, object> data1 = new hashmap<string, object> ();

Data1.put (...);

......

Users.insert (new basicdbobject (data1));//equivalent to Users.save (new basicdbobject (data1)

);

Insert method in the IV

String json = "{' database ': ' Mkyongdb ', ' table ': ' Hosting '," + "' detail ': {' Records ':", ' Index ': ' Vps_index1 ', ' acti ' ve ': ' True '}}} ";

DBObject data1 = (dbobject) JSON. Parse (JSON);

Users.insert (data1);//equivalent to Users.save (DATA1);

3.4java Query operation for collection

====================================

DBObject fields = new Basicdbobject ();

Fields.put ("_id", false);

Fields.put ("tag", true);

Fields.put ("Tv_sec", true);

Dbcursor cur = users.find (query,fields);

Can be used to filter fields that do not need to be fetched, reducing IO

====================================

Querying all the data find ()

Dbcursor cur = users.find (); while (Cur.hasnext ()) {...}

Query ID is greater than or equal to 1 and fetch only 10 records

Dbcursor cur = users.find (newbasicdbobject ("_id",newbasicdbobject ("$gte", 1)). Limit (10);

The query ID is greater than or equal to 1 records and is descending by ID-1 for Descending, 1 ascending.

Dbcursor cur = users.find (new Basicdbobject ("_id", Newbasicdbobject ("$gte", 1)). Sort (Newbasicdbobject ("_id",-1));

The query ID is greater than or equal to 1 and skips the first 10 records to show the equivalent of id>10

Dbcursor cur = users.find (newbasicdbobject ("_id",newbasicdbobject ("$gte", 1)). Skip (10);

A record with a query ID greater than or equal to 1 skips the first 10 records and displays only 10 records. Equivalent//paging function where id>10 and id<=20

Dbcursor cur = users.find (Newbasicdbobject ("_id", Newbasicdbobject ("$gte", 1)). Skip. Limit (10);

The number of all records with query ID greater than or equal to 1 returns INT type

Users.find (newbasicdbobject ("_id",newbasicdbobject ("$gte", 1)). COUNT ()

Findandremove () queries the _id=30000 data, and deletes

Users.findandremove (newbasicdbobject ("_id", 30000));

3.5java Update operation for collection

Query the record with ID 300, update the value of cust_id to 6533615, be sure to note the case, and the data//type, the return value of int means that the number of records affected can be Users.findone (newBasicdbobject ("_id", 300)); Look under, you will find this record//Only return two fields, respectively, _id,cust_id, the other fields are deleted.

Users.update (newbasicdbobject ("_id"), newbasicdbobject ("cust_id", "6533615")). GETN ();

This can be accomplished by updating only the cust_id value of ID 300 to 6533615, without deleting the other word of this record//segment property

Users.update (newbasicdbobject ("_id"), newbasicdbobject ("$set",newbasicdbobject (" cust_id "," 6533615 "))). GETN ();

3.6java Delete operation for collection

Removes data that is cust_id to 6533615. Note Using the Remove method does not free disk space.

MongoDB has only been flagged in collection and is not being deleted.

Users.remove (newbasicdbobject ("cust_id", "6533615")). GETN ();

To remove Id>=1 data

Users.remove (Newbasicdbobject ("_id", New Basicdbobject ("$gte", 1)). GETN ();

Removes the entire collection,drop and does not free up disk space

Users.drop ();

This week, using MongoDB in an experimental way, the application scenario is simple, so it's not very deep enough to know about MongoDB. This article mainly introduces MongoDB Java client programming, this aspect of the content is very simple, here is just a summary. It has to be said that the storage between KV and SQL, like MongoDB, is suitable for many Internet applications. MongoDB now has a lot of applications, and community activity is very high (there are many people in the country has a deep research, if there is time and energy, perhaps I will put some research on MongoDB), it is worth looking forward to.

To the bottom, the following summarizes the use of Java to develop MongoDB application of some bits. The most straightforward choice in Java and MongoDB interaction is to use the MongoDB Java Driver, which is: Http://github.com/mongodb/mongo-java-driver/downloads. In general, the API to manipulate MongoDB in Java is still very concise, and some of its common uses are described below.

1. Connect to the database

The sample code for establishing a connection with MongoDB is as follows:

Mongo m =new Mongo ("localhost", 27017); DB db = M.getdb ("Db_test");

Although the object db that represents the Db_test database connection for MongoDB is obtained here, there is no real connection with MongoDB, so even if the database does not rise then it will not throw an exception, although you still need to catch its instantiation process. MongoDB Java Driver The connection is pooled, so the application only need to instantiate a MONGO object, the operation of it is thread-safe, which is really convenient for development use.

2. Get Dbcollection

Collection in MongoDB uses dbcollection notation in Java (this is an abstract class, although you don't need to know), creating a Dbcollection instance is a line of code, just like creating DB instances, This operation does not involve real communication with the database.

Dbcollection coll = db.getcollection ("Collection1");

To get a "show tables" feature like MySQL, you can use the following code:

Set<string> colls = Db.getcollectionnames (); for (String s:colls) {System.out.println (s);} 3. Inserting documents

MongoDB stores the JSON-formatted document, and the simplest class in Java that represents this data format is map. The basicdbobject provided in MongoDB Java driver is a map (which inherits from the Linkedhashmap and implements the DBObject interface), which converts the data in the map to the Bson format for transmission to MongoDB. The following is an example of inserting a document:

Dbcollection coll=db.getcollection ("Collection1");

Basicdbobject doc=new basicdbobject ();

Doc.put ("name", "kafka0102");d oc.put ("Age", "page");d oc.put ("Time", Newdate ());

Coll.insert (DOC);

Each inserted document in MongoDB produces a unique identifier of _id. When Coll.insert (DOC) is called, driver checks if there is a _id field, and if not, automatically generates a Objectid instance as the _id value, which is encoded by 4 parts: The current time, machine ID, process number, and self-increment integer. The Insert function also supports inserting a document list:

Insert (list<dbobject> List)

The commit operation also has an update (DBObject Q, DBObject o), and remove (DBObject o).

4. Query document 4.1, FindOne

FindOne is the first record that the query satisfies the condition (it does not mean that the database meets the criteria for only one record), and the query condition is represented by DBObject, as shown in the following example:

Dbcollection coll=db.getcollection ("Collection1");

Basicdbobject cond=new basicdbobject ();

Cond.put ("name", "kafka0102"); Cond.put ("Age", 28);

DBObject Ret=coll.findone (cond); SYSTEM.OUT.PRINTLN (ret);

The returned result is a dbobject, which can be obtained by a get (key). For query criteria, a complex format can be represented by nesting multiple layers, such as:

Query=newbasicdbobject ();

Query.put ("I", New Basicdbobject ("$GT"),//e.g. find all where I > 50

4.2. Find

The Find function is a collection of queries, and the dbcursor that it returns is a dbobject iterator, using the following example:

Dbcollection coll=db.getcollection ("Collection1");

Basicdbobject cond=new Basicdbobject () cond.put ("I", New Basicdbobject ("$gt"). Append ("$lte", 30));

Dbcursor Ret=coll.find (cond);

while (Ret.hasnext ()) {System.out.println (Ret.next ());}

5. Use index

Create an index statement such as: Coll.createindex (New Basicdbobject ("I", 1)); , where I represents the field to index, and 1 indicates ascending (-1 means descending). As you can see, dbobject becomes a common structure representation for Java clients. View indexes using the Dbcollection.getindexinfo () function.

6. The concurrency of MongoDB Java driver

As mentioned earlier, the Java MongoDB driver uses the pooled processing of connections, which by default maintains 10 connections, which can be modified by option, using an instance of MONGO in the application. Each connection in the connection pool is represented by the Dbport structure (not dbcollection) and is stored in dbportpool, so the operation on Dbcollection does not imply the use of the same connection. If you need to ensure that you use the same connection during one request of your application, you can use the following code snippet:

DB db ...; Db.requeststart ();//code. Db.requestdone ();

The connection that is used between Requeststart and Requestdone is not from Dbportpool, but rather the threadlocal structure variable in the current thread (MyPort members are maintained in the Dbport).

7. Other options

Although Java MongoDB driver is good, it's like many people use ORM frameworks without using JDBC, and MongoDB's Java client has other options. 1) Support for Pojo and DAO. For those who are passionate about ORM, Morphia (Http://code.google.com/p/morphia/wiki/QuickStart) is a good choice for mapping by adding annotations to Pojo. and provides support for the DAO's crud operations. 2) support for DSL. Sculptor is such a thing, the user writes a neutral DSL file, sculptor translates it into code. This is usually not attractive, unless it is a multi-lingual application that translates a DSL into a variety of programming languages, otherwise there is no benefit in addition to increasing the cost of learning. 3) support for JDBC. Mongo-jdbc is something like this, but it's still experimental. It might be to get close to a Java programmer, but it's obviously not fully compatible with JDBC, and many Java programmers don't have a cold on JDBC, so it's not worth it.

This article is reproduced, the original address is:

Execute MongoDB under Java

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.