MongoDB installation (Linux)

Source: Internet
Author: User
Tags failover

Download file

Http://downloads.mongodb.org/linux/mongodb-linux-i686-static-2.5.0.tgz

Decompression: TAR-ZXVF Mongodb-linux-i686-static-2.5.0.taz renamed: MV mongodb-linux-i686-static-2.5.0 MongoDB

Create a database storage path and log path

The configuration file is as follows:

mongodb.conf#端口, the default is 27017port=27017# Database Path dbpath=/usr/mongodb/data/
#日志路径logpath =/usr/mongodb/log/mongodb.log
#日志文件是自动累加 instead of covering logappend=true
#用于关闭浏览器查看nohttpinterface =true Start./mongod-f mongodb.conf

Note: When you start, the export lc_all=c is required when the Locale::facet::_s_create_c_locale name not valid appears. 】

Some simple commands are "reproduced":

========= View Database =========
> Show DBS
Test

========= Switching Database =========
> Use test
Switched to DB test

========= View Collection =========
>show tables

Foo

System.indexes
Because no collection has been built, it returns NULL.

========= Set Merge Insert Data =========
> db.createcollection ("User");
{"OK": 1}

#再来查看一次集合, this time saw a set of two. The previous one seems to be used by the system.
> Show Tables

Foo

User
System.indexes

========= Inserting Data =========
Db.user.insert ({uid:1,username: "Liming", age:25});
Db.user.insert ({uid:2,username: "Bob", age:33});

========= View All data =========
> Db.user.find ();
{"_id": ObjectId ("5152917192c76fa290ed1a8e"), "UID": 1, "username": "Liming", "Age": 25}
{"_id": ObjectId ("515291a192c76fa290ed1a8f"), "UID": 2, "username": "Bob", "Age": 33}

========= Search By Field =========
> Db.user.find ({uid:2});
{"_id": ObjectId ("515291a192c76fa290ed1a8f"), "UID": 2, "username": "Bob", "Age": 33}
> Db.user.find ({username: "liming"});
{"_id": ObjectId ("5152917192c76fa290ed1a8e"), "UID": 1, "username": "Liming", "Age": 25}

From here you can see that MONGO is ideal for storing objects and JSON-formatted data, which is very flexible to use.


========= Supporting document Nesting =========
Db.user.insert ({IP: "127.0.0.1", ports:[{port:80}, {port:8080}]});
(You can also use Db.user.save, but insert is more consistent with the people we used to MySQL)

Did you notice that I inserted a completely different structure into the user table? Yes, for MongoDB, it's just a JSON that doesn't care about content.
> Db.user.find ();
{"_id": ObjectId ("5152917192c76fa290ed1a8e"), "UID": 1, "username": "Liming", "Age": 25}
{"_id": ObjectId ("515291a192c76fa290ed1a8f"), "UID": 2, "username": "Bob", "Age": 33}
{"_id": ObjectId ("5152931392c76fa290ed1a90"), "IP": "127.0.0.1", "ports": [{"Port": +}, {"Port": 8080}]}

Now check again.
> Db.user.find ({"Ports.port": "80"});
Why, why is there no result? Maybe the value type is wrong, let's change the order.
> Db.user.find ({"Ports.port": 80});
{"_id": ObjectId ("5152931392c76fa290ed1a90"), "IP": "127.0.0.1", "ports": [{"Port": +}, {"Port": 8080}]}
Does this mean that MONGO is a strong type?


========= other Query record command =========
Query a record:
> Db.user.findOne ();
{
"_id": ObjectId ("5152917192c76fa290ed1a8e"),
"UID": 1,
"username": "Liming",
"Age": 25
}

Query by criteria:
Db.user.find ({uid:2});

Regular query:
> Db.user.find ({username:/le/i});
{"_id": ObjectId ("5152917192c76fa290ed1a8e"), "UID": 1, "username": "Liming", "Age": 25}

Multi-Criteria Query:
> Db.user.find ({uid:1, username:/le/i});
{"_id": ObjectId ("5152917192c76fa290ed1a8e"), "UID": 1, "username": "Liming", "Age": 25}


========= Update =========
Db.user.update (qualification, {$set: Update content}, bool if it does not exist then insert, bool if more than one match condition is updated all)
Cases:
Db.user.update ({username: ' liming '}, {$set: {age:22}}, False, True)

========= Delete =========
Delete part of content db.user.remove ({IP: "127.0.0.1"})
Delete all content Db.user.remove ()
Delete Collection Db.user.drop ()

"Features and features of MongoDB"

Characteristics:
For collection storage, easy to store data for object types.
Mode of freedom.
Supports dynamic queries.
Supports full indexes, including internal objects.
Support Queries.
Supports replication and recovery.
Use efficient binary data storage, including large objects such as video.
Automatically process fragmentation to support scalability at the cloud level
Drivers for Python,php,ruby,java,c,c#,javascript,perl and C + + languages are supported, and drivers for Erlang and. NET platforms are also available in the community.
The file storage format is Bson (an extension of JSON).
can be accessed over the network.


Function:
Collection-oriented storage: suitable for storing objects and data in JSON form.
Dynamic query: MONGO supports rich query expressions. Query directives use a JSON-style tag to easily query objects and arrays embedded in the document.
Full index support: Includes embedded objects and arrays in the document. The query optimizer of MONGO parses the query expression and generates an efficient query plan.
Query monitoring: MONGO contains a monitoring tool to analyze the performance of database operations.
Replication and automatic failover: The MONGO database supports data replication between servers, supporting master-slave mode and inter-server replication. The primary goal of replication is to provide redundancy and automatic failover.
Efficient traditional storage: supports binary data and large objects (such as photos or pictures)
Auto-sharding to support cloud-scale scalability: Automatic sharding supports a level of database clustering, adding additional machines dynamically.


Applicable occasions:
Website data: MONGO is ideal for real-time inserts, updates and queries, as well as the replication and high scalability required for real-time data storage on the site.
Caching: Because of its high performance, MONGO is also suitable as a caching layer for the information infrastructure. After the system restarts, the persistent cache layer built by MONGO can avoid overloading the underlying data sources.
Large, low-value data: Storing some data in a traditional relational database can be expensive, and many times programmers often choose traditional files for storage.
Highly scalable scenario: The MONGO is ideal for databases made up of dozens of or hundreds of servers. Built-in support for the MapReduce engine is already included in the roadmap for MONGO.
Storage for objects and JSON data: The MONGO Bson data format is ideal for storing and querying in a document format.

A simple Java instance

 PackageCom.wangzhu.mongodb;Importjava.net.UnknownHostException;Importjava.util.ArrayList;Importjava.util.List;ImportJava.util.Random;ImportOrg.junit.After;ImportOrg.junit.Before;Importorg.junit.Test;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;ImportCom.mongodb.BasicDBObject;ImportCom.mongodb.DB;Importcom.mongodb.DBCollection;ImportCom.mongodb.DBCursor;ImportCom.mongodb.DBObject;ImportCom.mongodb.Mongo;Importcom.mongodb.MongoException; Public classTestmongodb {Private Static FinalLogger Logger =loggerfactory. GetLogger (Testmongodb.class); PrivateMongo Mongo; PrivateDB DB; @Before Public voidinit () {Try{MONGO=NewMongo ("192.168.1.103", 27017); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(mongoexception e) {e.printstacktrace (); } DB= Mongo.getdb ("Test"); } @After Public voiddestroy () {if(MONGO! =NULL) {mongo.close (); }    }    Privatedbcollection getdbconnetion (String name) {returndb.getcollection (name); } @Test Public voidTestquery () {dbcollection collection= This. Getdbconnetion ("User"); TestMongoDB.logger.info ("Find");  This. Print (Collection.find ()); TestMongoDB.logger.info ("Find" (uid:2));  This. Print (Collection.find (NewBasicdbobject ("UID", 2))); }    Private voidprint (dbcursor cursor) {TestMongoDB.logger.info ("-------Start---------");  while(Cursor.hasnext ()) {TestMongoDB.logger.info ("{}", Cursor.next ()); } TestMongoDB.logger.info ("-------End---------"); } @Test Public voidTestinsert () {dbcollection collection= This. Getdbconnetion ("User"); DBObject User=NewBasicdbobject (); User.put ("UID", 3); User.put ("Age", 43); User.put ("Name", "NULL");        Collection.insert (user); String[] Namearr= {"LiLi", "Wangsan", "Zhouhong", "Niefen", "Huyan",                "Zhusi" }; Random Random=NewRandom (); List<DBObject> list =NewArraylist<dbobject>();  for(inti = 4; I < 20; i++) {User=NewBasicdbobject (); User.put ("UID", i); User.put ("Age", I * random.nextint (20)); User.put ("Name", Namearr[i% 5]);        List.add (user);    } collection.insert (list); }}

MongoDB installation (Linux)

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.