Install and use MongoDB

Source: Internet
Author: User
Tags findone install mongodb

MongoDB is written by C ++ and its name comes from HuMongoIn the middle of the word "us", we can see from the name that its ambition lies in the processing of massive data. The simplest description of this database is scalable, high-performance, open source, schema-free, and document-oriented database. MongoDB's main goal is to build a bridge between key/value storage (providing high performance and high scalability) and traditional RDBMS systems (rich functions, combines the advantages of both.

Installation and use:

First install MongoDB on Ubuntu.

Download MongoDB, the latest production version 1.7.0

1. decompress the file.

$ Tar-xvf mongodb-linux-i686-1.4.3.tgz

2. Create a data directory for MongoDB. By default, it stores data in/data/DB

$ Sudo mkdir-P/data/DB/

$ Sudo chown 'id-U'/data/DB

3. Start the MongoDB service.

$ CD mongodb-linux-i686-1.4.3/bin

$./Mongod

4. Open another terminal and make sure that you are in the bin directory of MongoDB and enter the following command.

$./Mongo

Concepts

A mongod service can create multiple databases, and each database can have multiple tables. The table name here is collection, and each collection can store multiple documents ), each document is stored in the hard disk in the form of bson (Binary JSON), so it can store more complex data types. It is stored in a single document. You can add or delete fields for one or more documents without affecting other documents. This is called Schema-free, this is also the main advantage of document-based databases. Unlike the general key-value database, its value stores structure information, so you can perform read/write, statistics, and other operations on certain domains like relational databases. The biggest feature of Mongo is that it supports a very powerful query language. Its syntax is somewhat similar to an Object-Oriented Query Language. It can almost implement most of the functions similar to single-table queries in relational databases, it also supports data indexing. Mongo can also solve the query efficiency of massive data. According to official documents, when the data volume exceeds 50 GB, the Mongo database access speed is mysql10.
Times or more.

Bson

Bson is short for Binary JSON and is the binary encoding format of a JSON Document Object. Like JSON, bson allows you to insert document objects and arrays to other document objects and arrays, while extending the JSON data type. For example, bson has the date and bindate types.

Bson is compared to a binary exchange format, just like protocol buffers, but bson is more "schema-less" than it, which is very flexible but takes a little larger space.

Bson has the following three features:

1. lightweight

2. cross-platform

3. High Efficiency

Namespace

MongoDB stores bson objects to collections. These database names and collection names are called a namespace. For example, java. util. List; is used to manage data in the database.

Index

MongoDB can index a field, create a composite index, a unique index, or delete an index. Creating an index increases the overhead of space. By default, each table has a unique index: _ id. If _ id is not specified during data insertion, the service automatically generates a _ id. to make full use of existing indexes, reduce the space overhead. It is best to specify the key of a unique as _ id. It is usually appropriate to use the Object ID, such as the product ID.

 

Shell operation database:

 

1. Related to Super Users:

1. # enter the database Admin

Use Admin

2. # Add or modify user passwords

DB. adduser ('name', 'pwd ')

3. # view the user list

DB. system. Users. Find ()

4. # User Authentication

DB. Auth ('name', 'pwd ')

5. # delete a user

DB. removeuser ('name ')

6. # view all users

Show users

7. # view all databases

Show DBS

8. # view all collections

Show collections

9. # view the status of each collection

DB. printcollectionstats ()

10. # view master-slave replication status

DB. printreplicationinfo ()

11. # restore the database

DB. repairdatabase ()

12. # Set the record profiling, 0 = off 1 = slow 2 = all

DB. setprofilinglevel (1)

13. # view profiling

Show Profile

14. # copy a database

DB. copydatabase ('mail _ ADDR ', 'mail _ addr_tmp ')

15. # Delete collection

DB. mail_addr.drop ()

16. # Delete the current database

DB. dropdatabase ()

2. add, delete, and modify

1. # store nested objects

DB. foo. save ({'name': 'xy', 'address': {'city': 'beijinging', 'post': 100096}, 'phone': [138,139]})

 

2. # store array objects

DB. user_addr.save ({'uid': 'yushunzhi @ sohu.com ', 'al': ['test-1@sohu.com', 'test-2@sohu.com ']})

 

3. # modify according to query conditions. If the query condition does not exist, insert multiple records.

DB. Foo. Update ({'yy': 5}, {'$ set': {'xx': 2 }}, upsert = true, multi = true)

4. # delete records with YY = 5

DB. Foo. Remove ({'yy': 5 })

5. # delete all records

DB. Foo. Remove ()

 

3. Index

1. # Add an index: 1 (ascending),-1 (descending)

2. DB. Foo. ensureindex ({firstname: 1, lastname: 1 },{ unique: true });

3. # index sub-objects

4. DB. user_addr.ensureindex ({'al. Em ': 1 })

5. # View index information

6. DB. Foo. getindexes ()

7. DB. Foo. getindexkeys ()

8. # delete an index based on the index name

9. DB. user_addr.dropindex ('al. em_1 ')

 

4. Query

1. # search for all

2. DB. Foo. Find ()

3. # search for a record

4. DB. Foo. findone ()

5. # search 10 records based on conditions

6. DB. Foo. Find ({'msg ': 'Hello 1'}). Limit (10)

7. # Sort sorting

8. DB. deliver_status.find ({'from': 'ixigua @ Sina.com '}). Sort ({'dt',-1 })

9. DB. deliver_status.find (). Sort ({'ct ':-1}). limit (1)

10. # Count operation

11. DB. user_addr.count ()

12. # perform the distinct operation to query specified columns and repeat them.

13. DB. Foo. Distinct ('msg ')

14. # "> =" Operation

15. DB. Foo. Find ({"timestamp": {"$ GTE": 2 }})

16. # search for sub-objects

17. DB. Foo. Find ({'address. City': 'beijing '})

5. Management

1. # view the collection data size

2. DB. deliver_status.datasize ()

3. # view colleciont status

4. DB. deliver_status.stats ()

5. # query the size of all indexes

6. DB. deliver_status.totalindexsize ()

 

5. Advanced queries: Advanced Query


Conditional Operators
$ GT:>
$ LT: <
$ GTE:> =
$ LTE: <=
$ Ne :! =, <>
$ In: In
$ Nin: not in
$ All: All
$ Not: Anti-match (version 1.3.3 and later)

Query data with name <> "Bruce" and age> = 18
DB. Users. Find ({Name: {$ ne: "Bruce"}, age: {$ GTE: 18 }});

Query creation_date> '2017-01-01 'and creation_date <= '2017-12-31'
Data
DB. Users. Find ({creation_date: {$ GT: new date (2010,0, 1), $ LTE: new date (2010,11, 31 )});

Query age in (20, 22, 24, 26) data
DB. Users. Find ({age: {$ in: [20, 22, 24, 26]});

Query age modulo 10 equals 0
Data
DB. Users. Find ('this. Age % 10 = 0 ');
Or
DB. Users. Find ({age: {$ mod: [10, 0]});

Match All
DB. Users. Find ({favorite_number: {$ All: [6, 8]});
{Name: 'David ', age: 26, favorite_number: [6, 8, 9]}
{Name: 'David ', age: 26, favorite_number: [6, 7, 9]}

Query records that do not match name = B *
DB. Users. Find ({Name: {$ not:/^ B .*/}});
Query age modulo 10 not equal to 0
Data
DB. Users. Find ({age :{$ not :{$ mod: [10, 0] }});

# Some returned Fields
Select the returned age and _ id fields (the _ id field will always be returned)
DB. Users. Find ({}, {age: 1 });
DB. Users. Find ({}, {age: 3 });
DB. Users. Find ({}, {age: true });
DB. Users. Find ({name: "Bruce"}, {age: 1 });
0 is false, not 0 is true

Select the returned age, address, and _ id Fields
DB. Users. Find ({name: "Bruce"}, {age: 1, address: 1 });

Exclude returned age, address, and _ id Fields
DB. Users. Find ({}, {age: 0, address: false });
DB. Users. Find ({name: "Bruce"}, {age: 0, address: false });

Array Element count judgment
For {Name: 'David', age: 26, favorite_number: [6, 7, 9]} records
Match dB. Users. Find ({favorite_number :{$ size: 3 }});
Does not match dB. Users. Find ({favorite_number: {$ size: 2 }});

$ Exists
Query all records with name fields
DB. Users. Find ({Name: {$ exists: true }});
Query records that do not contain phone Fields
DB. Users. Find ({PHONE: {$ exists: false }});

$ Type determines the field type
Query all name fields of the character type
DB. Users. Find ({Name: {$ type: 2 }});
Query that all age fields are integer
DB. Users. Find ({age: {$ type: 16 }});

For character fields, you can use regular expressions.
Query all records with letters B or B leading
DB. Users. Find ({Name:/^ B. */I });

$ Elemmatch (1.3.1 and later)
Matches an element in an array field.

Javascript query and $ where Query
Query the records of age> 18. The query below is the same
DB. Users. Find ({age: {$ GT: 18 }});
DB. Users. Find ({$ where: "This. age> 18 "});
DB. Users. Find ("This. age> 18 ");
F = function () {return this. age> 18} dB. Users. Find (f );

Sort ()
ASC in ascending order of age
DB. Users. Find (). Sort ({age: 1 });
Desc in descending order of age
DB. Users. Find (). Sort ({age:-1 });

Limit the number of returned records ()
5 records are returned.
DB. Users. Find (). Limit (5 );
3 records are returned and information is printed.
DB. Users. Find (). Limit (3). foreach (function (User) {print ('My age is '+ User. Age )});
Result
My age is 18
My age is 19
My age is 20

Restrict the start point skip of the returned record ()
Returns 5 Records (limit 3, 5) starting from 3rd records)
DB. Users. Find (). Skip (3). Limit (5 );

Number of query records count ()
DB. Users. Find (). Count ();
DB. Users. Find ({age: 18}). Count ();
The number of all records in the User table is not 5.
DB. Users. Find (). Skip (10). Limit (5). Count ();
If you want to return the number of records after the limit, use count (true) or count (not 0)
DB. Users. Find (). Skip (10). Limit (5). Count (true );

Group ()
Assume that the test table only uses the following data
{Domain: "www.mongodb.org"
, Invoked_at: {d: "2009-11-011-03", T: "17:14:05 "}
, Response_time: 0.05
, Http_action: "Get/display/docs/aggregation"
}
Count: Count (*), total_time: sum (response_time), avg_time: total_time/count;
DB. Test. Group (
{Cond: {"invoked_at.d": {$ GT: "2009-11", $ LT: "2009-12 "}}
, Key: {http_action: true}
, Initial: {count: 0, total_time: 0}
, Reduce: function (Doc, out) {out. Count ++; out. total_time + = Doc. response_time}
, Finalize: function (out) {out. avg_time = out. total_time/out. Count}
});

[
{
"Http_action": "Get/display/docs/aggregation ",
"Count": 1,
"Total_time": 0.05,
"Avg_time": 0.05
}
]

 

Java application example

To use Java to operate MongoDB, You need to download a driver package from the official website. After importing the package, you can try to operate it (remember to drive the server)

First, we will introduce several common classes.

Mongo: Connect to the server and perform some database operations, such as creating a database.

DB: Corresponds to a database, which can be used to create a set and other operations

Dbcollection: Corresponds to a set (similar to a table), which may be the most used. You can add or delete records.

Dbobjec: Interface and basicdbobject object: indicates a specific record. basicdbobject implements dbobject. Because it is a key-value data structure, it is basically consistent with hashmap in use.

Dbcursor: Used to traverse the obtained data and implement iterable and iterator

Next, perform the following operations:

ImportJava.net. unknownhostexception;

ImportJava. util. List;

ImportJava. util. Set;

ImportCom. MongoDB. basicdbobject;

ImportCom. MongoDB. dB;

ImportCom. MongoDB. dbcollection;

ImportCom. MongoDB. dbcursor;

ImportCom. MongoDB. dbobject;

ImportCom. MongoDB. Mongo;

ImportCom. MongoDB. mongoexception;

Public classMongodbtest {

Public static voidMain (string [] ARGs)ThrowsUnknownhostexception, unknown exception {

// Mongo M = new Mongo ();

// Mongo M = new Mongo ("localhost ");

// Obtain the Database Service

Mongo M =NewMongo ("localhost", 27017 );

// Obtain the database mytest

DB = M. getdb ("mytest ");

// Obtain the names of all tables in the mytest database.

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

For(String S: colls ){

System.Out. Println (s );

}

// Obtain the testcollection table

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

// New A basicdbobject object Doc

Basicdbobject Doc =NewBasicdbobject ();

// Assign a value

Doc. Put ("name", "MongoDB ");

Doc. Put ("type", "Database ");

Doc. Put ("count", 1 );

// New basicdbobject object info

Basicdbobject info =NewBasicdbobject ();

Info. Put ("X", 203 );

Info. Put ("Y", 102 );

// Put info in Doc

Doc. Put ("info", Info );

// Insert a data entry to the testcollection table

Coll. insert (DOC );

// Query a piece of data

Dbobject mydoc = Coll. findone ();

System.Out. Println (mydoc );

// Insert 100 data records to testcollection cyclically

For(IntI = 0; I <100; I ++ ){

Coll. insert (NewBasicdbobject (). append ("I", I ));

}

// Counting statements in a collection

System.Out. Println (Coll. getcount ());

// Using a cursor to get all the documents

Dbcursor cur = Coll. Find ();

While(Cur. hasnext () {<span St

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.