First try MongoDB

Source: Internet
Author: User
Tags install mongodb mongodb 32 bit

1. MongoDB database Introduction

2. MongoDB Installation

3. MongoDB console Introduction

4. How to insert data to the database?

5. How to query the database?

6. java Database Operation example

7. Download Code

1. MongoDB database Introduction

The distributed CAP theory tells us that a distributed system cannot satisfy consistency, availability, and partition fault tolerance at the same time, and can only satisfy two of them. By writing update operations to transaction logs, relational databases achieve some durability, but reduce the write performance. MongoDB (not just SQL) Databases achieve high performance by reducing some features. MongoDB is taken from humongous and is an open source document database. MongoDB is a collection-oriented database in a free mode.

Some concepts of nosql databases are compared with conventional SQL databases (such as SQL server and oracle. MongoDB also contains the concept of a database. A database is a collection object called a collection object. A collection object is similar to a table in a traditional database. A collection object is a "Document Object ", in general, the opposite is the record of a traditional database. However, you must note that the databases and collections are created by lazy. That is to say, the collections and database files are created only when the data is actually inserted into the collection.

2. MongoDB Installation

I use the following test platform environment:

1. vmwarevm

2. ubuntu 10.04

It is relatively simple to install MongoDB In ubuntu. The command is as follows:

Xuqiang @ ubuntu :~ /Mongodb $ curl http://downloads.mongodb.org/linux/mongodb-linux-i686-1.6.4.tgz> mongo. tgzxuqiang @ ubuntu :~ /Mongodb $ tar xzf mongo. tgz

Go to the extracted directory:

Xuqiang @ ubuntu :~ /Mongodb $ cd mongodb-linux-i686-1.6.4/

The files in this directory are as follows:

 

Xuqiang @ ubuntu :~ /Mongodb/mongodb-linux-i686-1.6.4 $ lsbin GNU-AGPL-3.0 readme third-PARTY-NOTICES

Set the database file storage folder. By default, database files are stored in/data/db/. Therefore, you must first create the directory:

Xuqiang @ ubuntu :~ $ Sudo mkdir-p/data/db/

Change the permission of the directory:

Xuqiang @ ubuntu :~ $ Sudo chown 'id-U'/data/db

After preparing the file directory, start the server and enter the bin directory:

Xuqiang @ ubuntu :~ /Mongodb/mongodb-linux-i686-1.6.4 $ cd binxuqiang @ ubuntu :~ /Mongodb/mongodb-linux-i686-1.6.4/bin $ lsbsondump mongod export Export Import mongos unzip statmongo unzip dump program mongorestore unzip sniff use superuser to start the server:

Xuqiang @ ubuntu :~ /Mongodb/mongodb-linux-i686-1.6.4/bin $ sudo./mongod

Mongod mongodumpxuqiang @ ubuntu :~ /Mongodb/mongodb-linux-i686-1.6.4/bin $ sudo./mongod

The output is as follows:

./Mongod -- help for help and startup options

Sun Mar 27 04:26:17 MongoDB starting: pid = 6289 port = 27017 dbpath =/data/db/32-bit ** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data ** see http://blog.mongodb.org/post/137788967/32-bit-limitationsSun Mar 27 04:26:17 db version v1.6.4, pdfile version 4.5Sun Mar 27 04:26:17 git version: mongomar 27 04:26:17 sys info: linux domU-12-31-39-01-70-B4 2.6.21.7-2. fc8xen #1 SMP Fri Feb 15 12:39:36 EST 2008 i686 BOOST_LIB_VERSION = listen 37sun Mar 27 04:26:17 [initandlisten] waiting for connections on port 27017Sun Mar 27 04:26:18 [websvr] web admin interface listening on port 28017

The above view shows that the current server listens on port 27017, and the database files are stored in/data/db. Of course, if you do not want to enter the full path of the file in the command line, you can add the above path to the environment variable, or copy all the files under these bins to/usr/bin. After the server starts up, let's start the client program:

Open a bash console again and run the following command:

Xuqiang @ ubuntu :~ /Mongodb $ mongo

Output:

MongoDB shell version: 1.6.4

Connecting to: test> now the server has been started, and we have successfully connected to the server through the client. Haha, isn't it exciting? The following is a simple test:

> Db. foo. save ({a: 2 });

> Db. foo. find (); {"_ id": ObjectId ("4d8f216819225415327a66ae"), "a": 2}

 

Note that if the foo set does not exist in the test database, it is automatically created.

3. MongoDB console Introduction

MongoDB uses the javascript interactive console, from which you can directly operate the database. Enter help to view common help topics and enter the specific help topics. You can use the help command to get a preliminary understanding of the MongoDB command line. The js console has the command memory function. You can use the up and down arrows to view the previously typed commands.

> Help

Db. help () help on db methods db. mycoll. help () help on collection methods rs. help () help on replica set methods help connect connecting to a db help admin administrative help misc things to know show dbs show database names show collections in current database show users in current database show profile show most recent system. profile entries with time> = 1 ms use <db_name> set current database db. foo. find () list objects in collection foo db. foo. find ({a: 1}) list objects in foo where a = 1 it result of the last line evaluated; use to furtheriterate exit quit the mongo shell4. how to insert data to the database

The following test is performed in mydb. First, switch the database:

> Use mydb

Switched to db mydb

4.1 Insert command structure:

 

4.2 Example (http://www.mongodb.org/display/DOCS/Tutorial ):

> J = {name: "mongo" };{ "name": "mongo" }> t = {x: 3 };{ "x": 3}> db. things. save (j);> db. things. save (t);> db. things. find (); {"_ id": ObjectId ("4c2209f3924d31102bd84a"), "name": "mongo"} {"_ id": ObjectId ("4c2209fef3924d31102bd84b "), "x": 3} 5. how to query databases?

5.1 query basic structure:

 

5.2 use a cursor?

> Var cursor = db. things. find ();

> While (cursor. hasNext () printjson (cursor. next ());

Printjson is a built-in function.

5.3 how to add query conditions?

> Db. things. find ({name: "mongo "}). forEach (printjson); {"_ id": ObjectId ("4d8de0a325a9112df63a8c62"), "name": "mongo "}

The SQL statement equivalent to the preceding query is as follows:

SELECT * FROM things WHERE name = "mongo"

5.4 how to return only specific columns?

> Db. things. find ({x: 4}, {j: true }). forEach (printjson); {"_ id": ObjectId ("4d8de13a25a9112df63a8c64"), "j": 0}

Apparently, only the column j is returned.

5.5 how to limit the number of entries returned for query (used in paging )?

> Db. things. find (). limit (3); {"_ id": ObjectId ("4d8de0a325a9425df63a8c62"), "name": "mongo"} {"_ id": ObjectId ("relative "), "x": 3} {"_ id": ObjectId ("4d8de13a25a9425df63a8c64"), "x": 4, "j": 0} 6. java Database Operation example?

Import java. util. Set;

Import com. mongodb. DB; import com. mongodb. mongo; import com. mongodb. basicDBObject; import com. mongodb. DBCollection; import com. mongodb. DBObject; import com. mongodb. DBCursor; public class QuickTour {public static void main (String [] args) {try {System. out. println ("connect to server... "); // server, portMongo m = new Mongo (" localhost ", 27017); DB db = m. getDB ("mydb"); // get the collections Set <String> colls = db. getCollectionNames (); for (String s: colls) {System. out. println (s);} // insert into the db // make a new collectionDBCollection coll = db. getCollection ("testCollection"); BasicDBObject doc = new BasicDBObject (); doc. put ("name", "MongoDB"); doc. put ("type", "database"); doc. put ("count", 1); coll. insert (doc); // search db DBObject myDoc = coll. findOne (); System. out. println (myDoc); // use cursor to retrive data DBCursor cur = coll. find (); while (cur. hasNext () {System. out. println (cur. next () ;}} catch (Exception e) {System. out. println (e. toString ());}}} 7. Download Code

/Files/xuqiang/nosql/MongoDBTest.rar

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.