MongoDB Java API

Source: Internet
Author: User
Tags create index date now findone mongodb unique id
Original address: http://keben1983.blog.163.com/blog/static/143638081201010591157929/

This document is translated from the [mongodb-docs-2010-10-24.pdf] [Java Language Center] section of the document and is organized according to your own understanding.


Hope to give a friend like me to start contact a little help, but also make a memo, because is just learning, many of these features are currently not used, in the future, if what the function is not clear, you can directly consult the document.

MongoDB Java Driver Simple operation

First, Java-driven consistency



MongoDB Java driver is thread-safe, for general applications, as long as a MONGO instance, MONGO has a built-in connection pool (pool size defaults to 10).

For environments with lots of writing and reading, to ensure that the same db is used in a session, we can guarantee consistency in the following ways:

DB mdb = mongo.getdb (' dbname ');

Mdb.requeststart ();
//
Business code
//
Mdb.requestdone ();



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



Ii. Save/Find Objects (DBObject)



The Java driver provides a dbobject interface for us to save objects to the database.

Define the objects you want to save:

public class Tweet implements DBObject {
/** ...... */
}

Then we can use the object:

Tweet = new Tweet ();
Tweet.put ("User", userId);
Tweet.put ("message", message);
Tweet.put ("Date", new Date ());

Collection.insert (tweet);

When you query from the database, the results are automatically converted to DBObject objects, and we can convert to our own type:

Collection.setobjectclass (Tweet);

Tweet Mytweet = (tweet) collection.findone ();



Third, create a connection



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

DB db = M.getdb ("MyDB");

Note: In fact, the MONGO instance represents a database connection pool, and even in a multi-threaded environment, a MONGO instance is sufficient for us.

IV. Certification (optional)



Boolean auth = db.authenticate ("MyUserName", "mypasswd");

V. Get Collection List



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

for (String s:colls) {
SYSTEM.OUT.PRINLN (s);
}



Vi. acquiring a collection



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

Using Dbcollection, we can insert, query data, and other data operations.



Seven, insert the document



Suppose you have a JSON document that looks like this:

{
"Name": "MongoDB",
' type ': ' Database ',
"Count": 1,
"Info": {
x:203,
y:102
}
}

Note: The JSON document above has an inline document "info".

We can use Basicdbobject to create a document that is the same as the JSON above 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);

Viii. querying the first document (FindOne ())



To verify the data that is similar to the JSON we saved above, we can use the FindOne () method to get the data.

FindOne (): Returns a document;
Find (): Returns a cursor (dbcursor) that contains a set of objects dbobject;

DBObject doc = Coll.findone ();
System.out.println (DOC);

We'll see the console output:
{"_id": "49902cde5162504500b45c2c", "name": "MongoDB", "type": "Database", "Count": 1, "info": {"x": 203, "Y" : 102}, "_ns": "Testcollection"}

Nine, insert multiple documents



To show more query methods later, we first insert a few documents, and their JSON looks like this:
{
"I": value
}

To insert data using a loop:

for (int i = 0; i < i++) {
Coll.insert (New Basicdbobject (). Append ("I", I));
}

We note that the same Coll, we can insert different styles of data, this is the important feature of MongoDB "mode of freedom."

X. Statistics of documents



Now that we have 101 documents in the database, now count to see if it's right.

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

The console will output: 101

Xi. using cursors to obtain 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 output of the console is similar to the following:

{"_id": "49903677516250c1008d624e", "I": "," _ns ":" Testcollection "}

13. Query Document Collection



Depending on the query criteria, we can remove multiple objects from the database via dbcollection, such as querying the I>50 collection of documents:

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"), Append ("$lte", 30));

cursor = coll.find (query);

while (Cursor.hasnext ()) {
DBObject object = Cursor.next ();
System.out.println (object);
}



14. CREATE INDEX



MongoDB supports indexing, and adding an index to a dbcollection is simple, you just point to the field you want to create an index on, and then indicate whether it's ascending (1) or Descending (-1), such as creating an ascending index on "i".

Coll.createindex (New Basicdbobject ("I", 1)); 1 represents ascending

Query index



We can query all the indexes:

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

for (DBObject index:list) {
SYSTEM.OUT.PRINTLN (index);
}

The output of the console looks similar to the following:

{"Name": "I_1", "ns": "Mydb.testcollection", "key": {"I": 1}, "_ns": "System.indexes"}




The management function of MongoDB

First, get all the databases



Mongo m = new Mongo ();

For (String s:m.getdatabasenames ()) {
System.out.println (s);
}



Ii. deletion of the database



M.dropdatabase ("my_new_db");


Java type of MongoDB



One, Object ID



Objectid is used as a unique ID for automatic generation.

ObjectId id = new ObjectId ();
ObjectId copy = new ObjectId (ID);

Second, regular expressions



Pattern John = Pattern.compile ("Joh?n", case_insensitive);
DBObject query = new Basicdbobject ("name", John);

Query for all "name" matching/joh?n/i documents
dbcursor cursor = collection.find (query);



Iii. Date and time



Date now = new Date ();
DBObject time = new Basicdbobject ("TS", now);

Collection.save (time);

Iv. Database References



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 ();

Five or two in-process data



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

Six, embedded documents



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

In MongoDB, Java is represented as:

DBObject y = new Basicdbobject ("Y", 3);
DBObject x = new Basicdbobject ("x", y);

Seven, array



Any object that inherits from the list, in MongoDB, is treated as an array.

If you want to represent the following JSON data:

{
"X": [
1,
2,
{"foo": "Bar"},
4
]
}

In Java, you should:

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.