MongoDB Java API

Source: Internet
Author: User
Tags date now findone

Address: http://keben1983.blog.163.com/blog/static/143638081201010591157929/

This document is translated from the [Java language center] section of the document mongodb-docs-2010-10-24.pdf, which is compiled according to your own understanding.

I hope to give some help and memo to my friends who have started to contact me like this, because I just learned that many of these functions are currently unavailable. In the future, I am not sure what functions are available, you can also directly view this document.

MongoDB Java driver for simple operations

I. Java driver consistency

MongoDB Java drivers are thread-safe. For general applications, only one Mongo instance is required. Mongo has a built-in connection pool (the pool size is 10 by default ).

In an environment with a large number of writes and reads, we can use the following methods to ensure consistency when the same dB is used in a session:

Db mdb = Mongo. getdb ('dbname ');

MDB. requeststart ();
//
// Business Code
//
MDB. requestdone ();

DB and dbcollection are absolutely thread-safe, and they are cached, so the same object may be obtained in the application.

2. Save/find an object (dbobject)

The Java Driver provides the dbobject interface to save objects to the database.

Define the object to be saved:

Public class tweet implements dbobject {
/**......*/
}

Then we can use this object:

Tweet tweet = new tweet ();
Tweet. Put ("user", userid );
Tweet. Put ("message", message );
Tweet. Put ("date", new date ());

Collection. insert (Tweet );

When querying from a database, the results are automatically converted to dbobject objects. We can convert them to our own types:

Collection. setobjectclass (Tweet );

Tweet mytweet = (Tweet) collection. findone ();

3. Create a connection

Mongo M = new Mongo ();
Mongo M = new Mongo ("localhost ");
Mongo M = new Mongo ("localhost", 27017 );

DB = M. getdb ("mydb );

Note: In fact, a mongo instance represents a database connection pool. Even in a multi-threaded environment, a mongo instance is sufficient for us.

Iv. Authentication (optional)

Boolean auth = dB. Authenticate ("myusername", "mypasswd ");

5. Retrieve collection list

Set <string> colls = dB. getcollectionnames ();

For (string S: colls ){
System. Out. prinln (s );
}

6. Get a collection

Dbcollection coll = dB. getcollection ("testcollection ");

Using dbcollection, We can insert and query data.

VII. Insert a document

Suppose there is a JSON document as follows:

{
"Name": "MongoDB ",
"Type": "Database ",
"Count": 1,
"Info ":{
X: 203,
Y: 102
}
}

Note: The preceding JSON document has an embedded document "info ".

We can use basicdbobject to create a document that is the same as the preceding JSON and save it in MongoDB.

Dbobject Doc = new basicdbobject ();

Doc. Put ("name", "MongoDB ");
Doc. Put ("type", "Database ");
Doc. Put ("count", 1 );

Dbobject info = new basicdbobject ();
Info. Put ("X", 203 );
Info. Put ("Y", 102 );

Doc. Put ("info", Info );

Coll. insert (DOC );

8. query the first document (findone ())

To verify the JSON-like data stored above, we can use the findone () method to obtain the data.

Findone (): returns a document;
Find (): returns a cursor (dbcursor) that contains a group of objects dbobject;

Dbobject Doc = Coll. findone ();
System. Out. println (DOC );

We will see the console output:
{"_ Id": "49902cde5162504500b45c2c", "name": "MongoDB", "type": "Database", "Count": 1, "info ": {"X": 203, "Y": 102}, "_ ns": "testcollection "}

IX. Insert multiple documents

To show more query methods later, we first insert several documents whose JSON files are as follows:
{
"I": Value
}

Insert data in a loop:

For (INT I = 0; I <100; I ++ ){
Coll. insert (New basicdbobject (). append ("I", I ));
}

We have noticed that we can insert data of different styles in the same Coll, which is an important feature of MongoDB: "Free mode ".

10. Number of statistical documents

Now we have 101 documents in the database, and check whether the statistics are correct.

Long Count = Coll. getcount ();
System. Out. println (count );

The console will output 101

11. Use a cursor to retrieve all documents

Dbcursor cursor = Coll. Find ();

While (cursor. hasnext ()){
Dbobject object = cursor. Next ();
System. Out. println (object );
}

12. query a single document

Dbobject query = new basicdbobject ();

Query. Put ("I", 71 );

Cursor = Coll. Find (query );

While (cur. hasnext ()){
Dbobject object = cursor. Next ();
System. Out. println (object );
}

The console output is similar to the following:

{"_ Id": "49903677516250c1008d624e", "I": 71, "_ ns": "testcollection "}

13. query the document set

Based on the query conditions, we can use dbcollection to retrieve multiple objects from the database, such as querying the document set of I> 50:

Query = new basicdbobject ();

Query. Put ("I", new basicdbobject ("$ gt", 50); // I> 50

Cursor = Coll. Find (query );

While (cursor. hasnext ()){
Dbobject object = cursor. Next ();
System. Out. println (object );
}

For example, the query condition is 20 <I <= 30:

Query = new basicdbobject ();

// 20 <I <= 30
Query. Put ("I", new basicdbobject ("$ gt", 20). append ("$ LTE", 30 ));

Cursor = Coll. Find (query );

While (cursor. hasnext ()){
Dbobject object = cursor. Next ();
System. Out. println (object );
}

14. Create an index

MongoDB supports indexing, and it is very easy to add an index to a dbcollection. You only need to specify the fields to create the index, and then specify whether it is in ascending or descending order (-1, for example, create an index in ascending order on "I.

Coll. createindex (New basicdbobject ("I", 1); // 1 indicates Ascending Order

15. query Indexes

We can query all the indexes:

List <dbobject> List = Coll. getindexinfo ();

For (dbobject index: List ){
System. Out. println (INDEX );
}

The console output is similar to the following:

{"Name": "I _1", "ns": "mydb. testcollection "," key ": {" I ": 1}," _ ns ":" system. indexes "}

MongoDB Management Function

1. Obtain all databases

Mongo M = new Mongo ();

For (string S: M. getdatabasenames ()){
System. Out. println (s );
}

Ii. delete a database

M. dropdatabase ("my_new_db ");

Java type of MongoDB

1. Object ID

Objectid is used as the unique ID automatically generated.

Objectid id = new objectid ();
Objectid copy = new objectid (ID );

Ii. Regular Expressions

Pattern John = pattern. Compile ("Joh? N ", case_insensitive );
Dbobject query = new basicdbobject ("name", John );

// Query all "name" matches/Joh? N/I documentation
Dbcursor cursor = collection. Find (query );

Iii. Date and Time

Date Now = new date ();
Dbobject time = new basicdbobject ("ts", now );

Collection. Save (time );

Iv. Database reference

Dbref can be used to save database references.

Dbref addressref = new dbref (dB, "foo. Bar", address_id );
Dbobject address = addressref. Fetch ();

Dbobject person = basicdbobjectbuilder. Start ()
. Add ("name", "Fred ")
. Add ("Address", addressref)
. Get ();
Collection. Save (person );

Dbobject Fred = collection. findone ();
Dbref addressobj = (dbref) Fred. Get ("Address ");
Addressobj. Fetch ();

V. binary data

Byte array (byte []) is treated as binary data.

Vi. embedded documents

JSON data is as follows:
{
"X ":{
"Y": 3
}
}

In MongoDB, Java indicates:

Dbobject y = new basicdbobject ("Y", 3 );
Dbobject x = new basicdbobject ("X", y );

VII. Array

Any object inherited from list is considered as an array in MongoDB.

If you want to represent the following JSON data:

{
"X ":[
1,
2,
{"Foo": "bar "},
4
]
}

In Java, it should be:

List <Object> X = new arraylist <Object> ();
X. Add (1 );
X. Add (2 );
X. Add (New basicdbobject ("foo", "bar "));
X. Add (4 );

Dbobject Doc = new basicdbobject ("X", X );
System. Out. println (DOC );

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.