Getting Started with MongoDB simple introduction

Source: Internet
Author: User
Tags findone mongodb driver mongodb server

Information about MongoDB is now less, and most of the English site, most of the above content by the author translated from the official website, please translate or understand the error point please testify. After that I will continue to focus on MongoDB, and translate the "Developer zone" and "Admin zone" related content, please look forward to the next issue.

MongoDB is a database open source project based on distributed file storage. Written by the C + + language. Designed to provide a high-performance data storage solution for Web applications that can be sheathed.

It is characterized by high performance, easy to deploy, easy to use and easy to store data. The main features are:
* For collection storage, easy to store object type data.
* Free mode.
* Support Dynamic Query.
* Full index support, including internal objects.
* Support Query.
* Supports replication and recovery.
* Use efficient binary data storage, including large objects (such as video, etc.).
* Proactively handle fragmentation to support scalability at the cloud level
* Support multiple languages such as ruby,python,java,c++,php.
* File storage format is Bson (an extension of JSON)
* Internet access

The so-called "set-oriented" (collenction-orented), meaning that data is grouped in a dataset, is called a collection (collenction). Each collection has a unique identifying name in the database and can include an unlimited number of documents. The concept of a collection is similar to a table in a relational database (RDBMS), but it does not need to define any schema.
Mode Freedom (schema-free) means that for a file stored in a MongoDB database, we don't need to know what the structure definition is. If you need to, you can completely store files of different structures in the same database.
The documents stored in the collection are stored in the form of key-value pairs. The key is used to uniquely identify a document as a string type, whereas a value can be a complex file type in each. We call this storage format Bson (Binary serialized dOcument Format).

The MongoDB server is executable on Linux, Windows or OS X platforms, supports 32-bit and 64-bit applications, and the default port is 27017. Recommended for performing on 64-bit platforms due to MongoDB

The maximum file size supported for 32-bit mode execution is 2GB.

MongoDB stores the data in a file (the default path is:/data/db), which is managed using a memory-mapped file for increased efficiency.

Installation:
Linux/os x:
1 Creating a Data folder
Mkdir-p/data/db
2 Downloading a compressed package
Curl-o http://downloads.mongodb.org/linux/mongodb-linux-i686-latest.tgz
3 Extracting files
Tar xzf mongodb-linux-i386-latest.tgz
4 Starting the Service
Bin/mongod Run &
5 Using your own client connection
/bin/mongo
6 test
Db.foo.save ({a:1})
Db.foo.findOne ()

Under Windows:
1 Setting up the Data folder c:/data/db
2 Download the compressed package, unzip the file
3 Starting the Service
Bin/mongod.exe Run
4 Bring your own client
Bin/mongon.exe

The use of Linux and Windows system is very similar, different places are mainly the default data storage folder. Linux class System under/DATA/DB, while Windows

will be stored under the c:/data/db. The ability to specify the storage folder and start using--dbpath parameters at startup. such as: Bin/mongod.exe--dbpath D:/data/mongo

Frequent use of startup parameters:
Run to start directly. Example:./mongod Run
--DBPATH specifies that a specific storage folder is started and created if the folder does not exist. Example:./mongod--dbpath/var/data/mongo
--port the specified port to start. Example:./mongod--port 12345

To stop the MONGO service:
Method 1: Stop the server and use CTRL + C
Method 2: When the client stops, the client can be connected first
./mongo
and use the command
Db.shutdownerver ()
Then quit client
Exit

Using the Java language to manipulate MongoDB is easy, just to add the driver files to the classpath to be able to use.

1 Establishing the connection
To establish a MONGODB connection, you just have to specify the database you want to connect to. This database does not necessarily exist, assuming that it does not exist, MongoDB will build this for you first

Library. At the same time, you can specify the network address and port that you want to connect to in detail when connecting. Here are some examples of connecting to a native database:

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)
MongoDB services can be executed in Safe mode, at which point the client needs to use username and password when connecting to the database. Connections can be used in Java, for example, in the following ways:

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

Assuming Usernamepassword validation passed, the return value is true, otherwise false

3 Getting the collection list
Each database has 0 or more collections, and you can get a list of them when needed:

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

4 Getting a collection
To get a particular collection, you can specify the name of the collection and use the GetCollection () method:

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

When you acquire this collection object, you are able to make additions and deletions to the data and other operations.

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

Close.

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 using FindOne () to find the first document in a collection
To find the document that we inserted in the previous step, we can simply use the FindOne () operation 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 just one document or when we just inserted the first document, since there is no need to use the cursor at this time.

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

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

Note that the _id and _ns elements are actively adding your documents by MongoDB yourself. Remember: the element name used by MongoDB internal storage is started with "_".

7 Add multiple Documents
To do many other 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 are able to insert different types of documents in a collection, which is what we call "mode Freedom" (Schema-free).

8 Number of statistical documents
Using the GetCount () method

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

9 using the 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 agrees that we will iterate over the document that meets 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 were able to 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 a document with a value of 71 for the domain name "i":

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 a 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 indexes, and very easy to add indexes on the collection. To create an index, you only need to specify the attribute to be indexed, and specify ascending (1) or Descending (-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);
}

The MongoDB management function
The administrative 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: Get a Database object
Mongo m = admin.getdb ("MyDB");

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

15 storing Java objects with DBObject
The MongoDB for Java driver provides an interface for storing ordinary objects in the database 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, for example:

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 MongoDB, it takes its own initiative to convert the document to the DBObject interface type, and to instantiate it as your object, use the

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

Concurrency of Java drivers
The MongoDB driver for Java is thread-safe. Suppose you use it in a Web service, be able to create a singleton of it, and use it in all requests.

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

In environments with large requests, for example, you will often read the data you have just written.
For this, you need to use code such as the following:
Mongo m;
M.restartstart ();

Code .....

M.requestdone ();


The above describes the simple mongodb use, a lot of other information please refer to MongoDB API for Java.

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

Getting Started with MongoDB simple introduction

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.