Introductory Introduction to MongoDB

Source: Internet
Author: User
Tags findone mongodb mongodb server

Information about the MongoDB is now less, and most of the English web site, the above content mostly by the author translation from the official website, please translate or understand the wrong place please testify. After the author will continue to pay attention to MongoDB, and translation of "Developer Zone" and "Admin Zone" related content, please look forward to the next period of content.

MongoDB is a database open source project based on distributed file storage. Written by the C + + language. A high-performance data storage solution designed to provide an exhibition for Web applications.

It is characterized by high-performance, easy to deploy, easy to use, storage data is very convenient. The main functional characteristics are:
* Oriented to collection storage, easy to store data of object type.
* Mode free.
* Support Dynamic Query.
* Supports full indexing, containing internal objects.
* Support Queries.
* Support for replication and recovery.
* Use efficient binary data storage, including large objects such as video.
* Automatically handle fragmentation to support cloud level scalability
* Support ruby,python,java,c++,php and many other languages.
* File storage format is Bson (an extension of JSON)
* Accessible via Network

The so-called "set-oriented" (collenction-orented) means that data is grouped in a dataset and is called a set (Collenction). Each collection has a unique identification name in the database and can contain an unlimited number of documents. The concept of a set is similar to a table in a relational database (RDBMS), but it does not need to define any schema (schema).
Mode Freedom (schema-free) means that we do not need to know any of its structural definitions for files stored in the MongoDB database. If necessary, you can store files of different structures in the same database.
A document stored in a collection that is stored as a key-value pair. Keys are used to uniquely identify a document, a string type, and a value can be a complex file type in each. We call this storage form Bson (Binary serialized dOcument format).

The MongoDB server can run on Linux, Windows, or OS X platforms, supporting 32-bit and 64-bit applications with a default port of 27017. Recommended to run on the 64-bit platform because MongoDB

The maximum file size supported in 32-bit mode runs is 2GB.

MongoDB stores the data in a file (the default path is:/data/db) and manages it with a memory-mapped file for increased efficiency.

Installation:
Linux/os x below:
1 Establishing the Data directory
Mkdir-p/data/db
2 Download Compression Package
Curl-o http://downloads.mongodb.org/linux/mongodb-linux-i686-latest.tgz
3 Decompression File
Tar xzf mongodb-linux-i386-latest.tgz
4 Start Service
Bin/mongod Run &
5 using a self-connected client connection
/bin/mongo
6 test
Db.foo.save ({a:1})
Db.foo.findOne ()

Under Windows:
1 Set up data directory c:/data/db
2 Download Compressed package, extract files
3 Start Service
Bin/mongod.exe Run
4 Self-with client
Bin/mongon.exe

Linux and Windows systems use the same, different places are mainly the default data storage directory. Linux class systems are stored under/DATA/DB, while Windows

will be stored under the c:/data/db. You can use the--dbpath parameter to specify the storage directory at startup and start. such as: Bin/mongod.exe--dbpath D:/data/mongo

Common Startup parameters:
Run starts directly. Example:./mongod Run
--DBPATH specifies that a specific storage directory is started and created if the directory does not exist. Example:./mongod--dbpath/var/data/mongo
--PORT Specifies that the port is started. Example:./mongod--port 12345

Stop MONGO Service:
Method 1: Service-side stop, can use CTRL + C
Method 2: At the client stop, you can connect to the client first
./mongo
and use the command
Db.shutdownerver ()
Then exit the client
Exit

Using the Java language to manipulate MongoDB is very simple, as long as you add a driver file to classpath.

1 Establishing the connection
To establish a MONGODB connection, you can simply specify the database to connect to. This database does not necessarily exist, and if it does not exist, MongoDB will build it for you first.

Library. Also, you can specify the network address and port to which you want to connect when connecting. The following are some examples of connecting native databases:

Import Com.mongodb.Mongo;
Import com.mongodb.DBCollection;
Import Com.mongodb.BasicDBObject;
Import Com.mongodb.DBObject;
Import Com.mongodb.DBCursor;
Import Com.mongodb.MongoAdmin;

Mongo db = new Mongo ("MyDB");
Mongo db = new Mongo ("localhost", "mydb");
Mongo db = new Mongo ("localhost", 27017, "mydb");

2 Security verification (not required)
The MongoDB service can run in Safe mode when any client needs to connect to the database using a username and password. In Java, you can connect by using the following methods:

Boolean auth = db.authenticate (userName, password);

True if user name password authentication is passed, or false

3 Getting the list of collections
There are 0 or more collections in each database, and you can get their lists when you need them:

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

4 Get a set
To get a specific set, you can specify the name of the collection and use the GetCollection () method:

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

When you get this collection object, you can change the data to check and modify the operation.

5 Inserting documents
When you get a collection object, you can insert the document into the object. For example, there is a JSON-like small document:
{
"Name": "MongoDB",
' type ': ' Database ',
"Count": 1,
"Info": {
x:203,
y:102
}
}
Please note that this document contains an internal document. We can use the Basicdbobject class to create this document and use the Insert () method to easily insert it into the set

Close in.

Basicdbobject doc = new Basicdbobject ();
Doc.put ("name", "MongoDB");
Doc.put ("type", "database");
Doc.put ("Count", 1);

Basicdbobject info = new Basicdbobject ();
Info.put ("x", 203);
Info.put ("Y", 102);

Doc.put ("info", info);

Coll.insert (DOC);

6 use FindOne () to find the first document in the collection
To find the document that we inserted in the previous step, we can simply use the FindOne () action to get the first document in the collection. This method returns a single document (this is relative to the return of the Find () operation using dbcursor), which is useful for only one document or we just inserted the first document, because there is no need to use the cursor at this point.

DBObject MyDoc = Coll.findone ();
System.out.println (MYDOC);

Returns a similar:
{
"_id": "ac907a1f5b9d5e4a233ed300",
"Name": "MongoDB",
' Type ': 1,
"Info": {
"X": 203,
"Y": 102},
"_ns": "Testcollection"
}

Note that the _id and _ns elements are automatically added to your document by MongoDB. Remember: the element name used for MongoDB internal storage is started with "_".

7 Adding multiple documents
To do more interesting query experiments, let's add a variety of document types to the collection, like this:
{
"I": value
}
Can be implemented through loops

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

Note that we can insert different types of documents in a collection, which is what we call "mode Freedom" (Schema-free).

8 Statistics Number of documents
Using the GetCount () method

System.out.println (Coll.getcount ());

9 Use the cursor (cursor) to get all the documents
In order to get all the documents in the collection, we can use the Find () method. This method returns a Dbcursor object that allows us to iterate over the document that matches the query criteria

Come out.

Dbcursor cur = coll.find ();
while (Cur.hasnext ()) {
System.out.println (Cur.next ());
}

10 getting a single document in a query
We can create a query and pass it to the Find () method to get a subset of all the documents in the collection. For example, we want to query for a document with a domain name of "I" and a value of 71:

Basicdbobject query = new Basicdbobject ();
Query.put ("I", 71);
cur = coll.find (query);
while (Cur.hasnext ()) {
System.out.println (Cur.next ());
}

11 using a conditional query to get the collection
For example, we want to query all I>50 documents:

Basicdbobject query = new Basicdbobject ();
Query.put ("I", New Basicdbobject ("$gt", 50));
cur = coll.find (query);
while (Cur.hasnext ()) {
System.out.println (Cur.next ());
}

Of course, we can also do the < I <= 30 query

Basicdbobject query = new Basicdbobject ();
Query.put ("I", New Basicdbobject ("$gt"), Append ("$lte", 30));
cur = coll.find (query);
while (Cur.hasnext ()) {
System.out.println (Cur.next ());
}

12 Creating an Index
MongoDB supports indexing, and it is easy to add indexes to the collection. To create an index, you only need to specify the property to index, and specify ascending (1) or descending order (-1).

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

13 Getting the index list

list<dbobject> list = Coll.getindexinfo ();
for (DBObject o:list) {
System.out.println (o);
}

MongoDB management function
The management functions are defined in the Com.mongodb.MongoAdmin class.
Example a: Getting a list of databases
Mongoadmin admin = new mongoadmin ();
For (String s:admin.getdatabasenames ()) {
System.out.println (s);
}

Example B: Getting database objects
Mongo m = admin.getdb ("MyDB");

Example c: Deleting a database
Admin.dropdatabase ("MyDB");

15 storing Java objects with DBObject
An interface for storing ordinary objects in a database is provided in the MongoDB for Java driver dbobject
For example, there is an object class tweet that needs to be stored
public class Tweet implements dbobject{
/*...*/
}
You can use the following code:

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

Collection.insert (Mytweet);

When a document is taken out of the MongoDB, it automatically converts the document into a DBObject interface type, which is instantiated as your object, using the

Dbcollection.setobjectclass ().
Collection.setobjectclass (Tweet);
Tweet Mytweet = (tweet) collection.findone ();

Java-driven concurrency
Java's MongoDB drive is thread-safe. If you use it in a Web service, you can create a single instance of it and use it in all requests.

However, if you need to ensure transactional consistency in a session (such as an HTTP request), you may want to use the same port for the driver in this session. This is only in

In an environment where requests are very large, for example, you will often read the data just written.
To do this, you need to use the following code:
Mongo m;
M.restartstart ();

Code .....

M.requestdone ();


For more information, please refer to the MongoDB API for Java with a simple mongodb.

Official homepage: http://www.mongodb.org/display/DOCS/Home

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.