Java programming for MongoDB

Source: Internet
Author: User
Tags findone mongodb driver

This week, we tried to use MongoDB in a very simple application scenario, so we do not know much about MongoDB. This article mainly introduces the Java client programming of MongoDB, which is also very simple. Here is a summary. I have to say that storage between kV and SQL such as MongoDB is suitable for many Internet applications. MongoDB currently has many application cases, and the Community is very active (many people in China have studied it very deeply. If you have time and energy, maybe I will also invest in some research on MongoDB). It is worth looking forward.

Let's get down to the truth. Next we will summarize some of the things about using Java to develop MongoDB applications. The most direct choice for interacting with MongoDB in Java is to use the MongoDB Java driver, which is: http://github.com/mongodb/developer-java-driver/downloads. In general, the APIs used to operate MongoDB in Java are still very concise. I will introduce some of its common usage.

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 connection of MongoDB's db_test database is obtained here, there is no real connection with MongoDB, so even if the database does not get up, no exception will be thrown, although you still need to catch its instantiation process. MongoDB Java driver performs pooled processing on the connection. Therefore, only one Mongo object needs to be instantiated in the application. The operations on the Mongo object are thread-safe, this is really convenient for development and use.

2. Get dbcollection

Collection in MongoDB is represented by dbcollection in Java (this is an abstract class, although you do not need to know). Creating a dbcollection instance is also a line of code, just like creating a DB instance, this operation does not involve real communication with databases.

DBCollection coll = db.getCollection("collection1");

To obtain the "show tables" function similar to MySQL, you can use the following code:

Set<String> colls = db.getCollectionNames();for (String s : colls) {    System.out.println(s);}
3. Insert a document

MongoDB stores documents in JSON format, and map is the simplest class in Java that represents this data format. The basicdbobject provided by the MongoDB Java driver is a map (which inherits from linkedhashmap and implements the dbobject interface). It converts the data in the map to the bson format and transmits it to MongoDB. The following is an example of inserting a document:

DBCollection coll = db.getCollection("collection1");BasicDBObject doc = new BasicDBObject();doc.put("name", "kafka0102");doc.put("age", 28);doc.put("time", new Date());coll.insert(doc);

Each inserted document in MongoDB generates a unique identifier _ id. When you call Coll. insert (DOC);, the driver checks whether the _ id field exists. If not, the objectid instance is automatically generated as the _ id value. This objectid is encoded in four parts: the current time, machine ID, process number, and auto-increment integer.
The insert function also supports inserting the document list:

insert(List<DBObject> list)

The commit operations include update (dbobject Q, dbobject O) and remove (dbobject O ).

4. query documents 4.1 and findone

Findone is the first record that meets the condition (it does not mean that the database only has one record that meets the condition). 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 set by get (key. For query conditions, you can use nested layers to express complex formats, such:

query = new BasicDBObject();        query.put("i", new BasicDBObject("$gt", 50));  // e.g. find all where i > 50
4.2. Find

The find function is used to query a set. The returned dbcursor is the dbobject iterator. The example is as follows:

DBCollection coll = db.getCollection("collection1");BasicDBObject cond = new BasicDBObject();cond.put("i", new BasicDBObject("$gt", 20).append("$lte", 30));DBCursor ret = coll.find(cond);while(ret.hasNext()) {   System.out.println(ret.next());}
5. Use Indexes

Create an index statement, for example, Coll. createindex (New basicdbobject ("I", 1); where I indicates the field to be indexed, 1 indicates ascending (-1 indicates descending ). As you can see, dbobject becomes a common structure representation of the Java client. View indexes using the dbcollection. getindexinfo () function.

6. MongoDB Java driver concurrency

As mentioned above, the Java MongoDB driver uses a pooled connection. By default, this connection pool maintains 10 connections. You can use option to modify the connection pool and use an instance of Mongo in the application. Each connection in the connection pool is represented by the dbport structure (rather than the dbcollection) and stored in the dbportpool. Therefore, operations on the dbcollection do not mean that the same connection is used. If you need to use the same connection during a request of the application, you can use the following code snippet:

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

The connection used between requeststart and requestdone is not from dbportpool, but the threadlocal structure variable in the current thread (dbport member is maintained in myport ).

7. Other options

Although Java MongoDB driver is good, many people use some ORM frameworks instead of JDBC, and MongoDB's Java client also has other options.
1) Support for pojo and Dao. For those who are keen on Orm, morphia (http://code.google.com/p/morphia/wiki/QuickStart) is a good option to map by adding annotations to pojo and providing support for crud operations on Dao.
2) DSL support. Sculptor is something like this. The user writes a neutral DSL file and sculptor translates it into code. This is usually not attractive. Unless it is a multi-language application that can translate DSL into multiple programming languages, there is no benefit in addition to increasing the learning cost.
3) support for JDBC. Mongo-JDBC is something like this, but it is still experimental. It may want to be close to Java programmers, but it is obviously not fully compatible with JDBC, and many Java programmers do not catch up with JDBC, so it is not very worth using.

================================ Gorgeous Terminator ====== ======================================

Author:Kafka0102
Link: http://www.kafka0102.com/2010/07/209.html

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.