Official MongoDB tutorial

Source: Internet
Author: User
Tags findone mongodb server mongodb tutorial mongodb windows tojson mongo shell

The platform uses Win32 as an example. The content is from the official website and is sorted out.

Refer:

Http://wiki.mongodb.org/display/DOCS/Quickstart+Windows

Http://www.mongodb.org/display/DOCS/Tutorial

Chinese document:

Http://wiki.mongodb.org/display/DOCS/Home

The "Chinese" link of the following translations

 

1. Download pre-compiled binary

Select 32bit and 64bit

We recommend that you use a 64-bit version of Windows to run a 64-bit version of MongoDB.

Http://wiki.mongodb.org/display/DOCS/Downloads

After decompression, you can change the directory name to Mongo-xxxxxxx to indicate differentiation.

 

2. Create a data directory

In Windows, the default data directory is stored in the disk where the MongoDB binary is located.

For example, Mongo under C:/will be stored in C:/data/DB,

However, it is not automatically created and must be created manually.

C:/> mkdir/Data

C:/> mkdir/data/DB

 

3. Run the MongoDB Server

The most important binary file is: Data Warehouse service provider d.exeand management tool cmd.exe

In C:/my_1__dir/bin, run the following command to start the server:

C:/> Cd/my_1__dir/bin

C:/my_1__dir/bin> mongod

Use a command line similar

Mongod -- bind_ip 127.0.0.1 -- logpath D:/Mongo/logs -- logappend -- dbpath D:/Mongo/data -- directoryperdb -- install

Where

Mongod -- install

Mongod -- service

Mongod -- remove

Mongod -- reinstall

You can add or delete services.

-- Servicename {Arg}

-- Serviceuser {Arg}

-- Servicepassword {Arg}

Set Service Information

 

4. Use cmd.exe to test simple JavaScript statements

C:/> Cd/my_1__dir/bin

C:/my_1__dir/bin> Mongo

> // The Mongo shell is a javascript shell connected to the DB

> 3 + 3

6

> DB

Test

> // The first write will create the DB:

> DB. Foo. insert ({A: 1 })

> DB. Foo. Find ()

{_ ID:..., A: 1}

For more information about how to use .exe, see cmd.exe -- help.

 

5. (optional) Use vs to compile the MongoDB Windows version.

For details, see

Http://wiki.mongodb.org/display/DOCS/Building+for+Windows

 

6. Comparison between SQL and MongoDB

MongoDB has similar query capabilities with relational databases (such as MySQL), but the query syntax is different.

Http://www.mongodb.org/display/DOCS/ SQL +to+Mongo+Mapping+Chart

MongoDB requests (including index key styles) are expressed as JSON (bson) objects,

It also contains an actual verb (such as find ).

The following is a comparison between the SQL and Alibaba request Language sentences (you can run the command line "cmd.exe)

(Note: Not necessarily equivalent. Some operations have their own unique rules in different databases,

For example, MySQL, so be extremely careful)

(1) Create

Create Table users (a number, B number)

(Implicit, but can also be explicitly created, such as a cap set)

> # Mongo Shell

> DB. createcollection ("mycoll", {capped: True, size: 100000 })

> Show collections

If the driver supports

> DB. runcommand ({createcollection: "mycoll", capped: True, size: 100000 })

(2) Insert

Insert into users values (1, 1)

> DB. Users. insert ({A: 1, B: 1 })

(3) Query

Select a, B from users

> DB. Users. Find ({}, {A: 1, B: 1 })

Select * from users

> DB. Users. Find ()

Select * from users where age = 33

> DB. Users. Find ({age: 33 })

Select a, B from users where age = 33

> DB. Users. Find ({age: 33}, {A: 1, B: 1 })

Select * from users where age = 33 order by name

> DB. Users. Find ({age: 33}). Sort ({Name: 1 })

Select * from users where age> 33

> DB. Users. Find ({'age': {$ GT: 33 }})

> DB. Users. Find ({age: {$ GT: 33 }})

Select * from users where age <33

> DB. Users. Find ({'age': {$ LT: 33 }})

> DB. Users. Find ({age: {$ LT: 33 }})

Select * from users where a = 1 and B = 'Q'

> DB. Users. Find ({A: 1, B: 'q '})

(4) Update (20110311 update: including Delete ?)

Update users set a = 1 Where B = 'Q'

> DB. Users. Update ({B: 'q'}, {$ set: {A: 1 }}, false, true)

(5) Index

Create index myindexname on users (name)

> DB. Users. ensureindex ({Name: 1 })

Explain select * from users where z = 3

> DB. Users. Find ({z: 3}). Explain ()

(6) set functions, sorting, paging, and other queries

Select * from users order by name DESC

> DB. Users. Find (). Sort ({Name:-1 })

Select * from users limit 10 skip 20

> DB. Users. Find (). Limit (10). Skip (20)

Select * from users limit 1

> DB. Users. findone ()

Select distinct last_name from users

> DB. Users. Distinct ('Last _ name ')

Select count (* Y) from users

> DB. Users. Count ()

Select count (* Y) from users where age> 30

> DB. Users. Find ({age: {'$ GT': 30}). Count ()

Select count (AGE) from users

> DB. Users. Find ({age: {'$ exists': true}). Count ()

For more detailed usage, see the manual

Http://www.mongodb.org/display/DOCS/Manual

 

7. Use cmd.exe to manage databases

Double-click cmd.exe

Connect to the test database of localhost by default.

MongoDB shell version: 1.6.3

Connecting to: Test

>

Switch database (it may not exist)

MongoDB does not require explicit creation of database sets, but is automatically created when data is inserted.

If the collection does not exist, MongoDB considers it a null collection.

Switching databases with use does not immediately create a database, but is created only when data is inserted.

So show DBs will not immediately display the database

> Use mydb

Switched to DB mydb

Show all databases

> Show DBS

Admin

Local

Test

View help:

> Help

DB. Help () Help on DB Methods

DB. mycoll. Help () Help on collection methods

Rs. Help () Help on replica set methods

Help connect ing to a DB help

Help admin administrative help

Help MISC things to know

 

Show DBS show database names

Show collections show collections in current database

Show users show users in current database

Show profile show most recent system. Profile entries wit

H 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 F

Urther iterate

Exit quit the Mongo Shell

Create a variable, assign a value, save it to the set, and read it out.

The following rules are implicitly applied:

You do not need to create a set;

The structure is dynamically changeable and heterogeneous objects can be put together;

Automatically add the _ id field;

The objectid value is unique.

> J = {name: "mongo "};

{"Name": "mongo "}

> T = {X: 3 };

{"X": 3}

> DB. Things. Save (j );

> DB. Things. Save (t );

> DB. Things. Find ();

{"_ Id": objectid ("4c2209f9f3924d31102bd84a"), "name": "mongo "}

{"_ Id": objectid ("4c2209fef3924d31102bd84b"), "x": 3}

Loop insertion. If more than 20 items are displayed, the first 20 items are displayed. continue with it.

Find () returns the cursor object

> For (VAR I = 1; I <= 20; I ++) dB. Things. Save ({X: 4, J: I });

> DB. Things. Find ();

{"_ Id": objectid ("4c2209f9f3924d31102bd84a"), "name": "mongo "}

{"_ Id": objectid ("4c2209fef3924d31102bd84b"), "x": 3}

{"_ Id": objectid ("4c220a42f3924d31102bd856"), "x": 4, "J": 1}

{"_ Id": objectid ("4c220a42f3924d31102bd857"), "x": 4, "J": 2}

{"_ Id": objectid ("4c220a42f3924d31102bd858"), "x": 4, "J": 3}

{"_ Id": objectid ("4c220a42f3924d31102bd859"), "x": 4, "J": 4}

{"_ Id": objectid ("4c220a42f3924d31102bd85a"), "x": 4, "J": 5}

{"_ Id": objectid ("4c220a42f3924d31102bd85b"), "x": 4, "J": 6}

{"_ Id": objectid ("4c220a42f3924d31102bd85c"), "x": 4, "J": 7}

{"_ Id": objectid ("4c220a42f3924d31102bd85d"), "x": 4, "J": 8}

{"_ Id": objectid ("4c220a42f3924d31102bd85e"), "x": 4, "J": 9}

{"_ Id": objectid ("4c220a42f3924d31102bd85f"), "x": 4, "J": 10}

{"_ Id": objectid ("4c220a42f3924d31102bd860"), "x": 4, "J": 11}

{"_ Id": objectid ("4c220a42f3924d31102bd861"), "x": 4, "J": 12}

{"_ Id": objectid ("4c220a42f3924d31102bd862"), "x": 4, "J": 13}

{"_ Id": objectid ("4c220a42f3924d31102bd863"), "x": 4, "J": 14}

{"_ Id": objectid ("4c220a42f3924d31102bd864"), "x": 4, "J": 15}

{"_ Id": objectid ("4c220a42f3924d31102bd865"), "x": 4, "J": 16}

{"_ Id": objectid ("4c220a42f3924d31102bd866"), "x": 4, "J": 17}

{"_ Id": objectid ("4c220a42f3924d31102bd867"), "x": 4, "J": 18}

Has more

> It

{"_ Id": objectid ("4c220a42f3924d31102bd868"), "x": 4, "J": 19}

{"_ Id": objectid ("4c220a42f3924d31102bd869"), "x": 4, "J": 20}

You can save the cursor variables explicitly, and then operate (beautify the document with the built-in tojson)

> Var cursor = dB. Things. Find ();

> While (cursor. hasnext () printjson (cursor. Next ());

You can also use foreach () to execute a loop (but you need to define a special function)

> DB. Things. Find (). foreach (printjson );

The cursor can be used as an array.

At this time, all the data is loaded into the memory, and a large result set may cause memory overflow.

So try to use it as an iterator

> Var cursor = dB. Things. Find ();

> Printjson (cursor [4]);

Can be converted to an array (the array concept is not applicable to drivers, but only for interactive interfaces)

> Var arr = dB. Things. Find (). toarray ();

> Arr [5];

{"_ Id": objectid ("4c220a42f3924d31102bd859"), "x": 4, "J": 4}

Because the MongoDB cursor is not a snapshot,

Therefore, the operation between the first and last next () may or may not affect the query results.

In this case, you need to use the lock snapshot to query.

MongoDB has similar query capabilities with SQL,

Generally, you need to create a "query document" (that is, the JSON object that is used as the parameter)

For example:

Select * from things where name = "mongo"

> DB. Things. Find ({name: "mongo"}). foreach (printjson );

Select * from things where x = 4

> DB. Things. Find ({X: 4}). foreach (printjson );

{A: A, B: B,...} Means

Where a = A and B = B and ..."

Reference http://www.mongodb.org/display/DOCS/Queries+and+Cursors

MongoDB also allows the return of "some documents" by specifying a subset of elements in the second parameter of find.

Note: The _ id field always needs to be returned.

Select J from things where x = 4

> DB. Things. Find ({X: 4}, {J: true}). foreach (printjson );

To facilitate cursor processing, Mongo and drivers provide findone () query documents.

Like the find () parameter, the return is not a cursor, but the first document or null that meets the conditions.

This method is efficient, reducing the workload of databases and clients,

> Printjson (db. Things. findone ({name: "mongo "}));

Equivalent to find ({name: "mongo"}). limit (1)

You can use limit () to limit the result size.

The benefits are the same as those of findone.

> DB. Things. Find (). Limit (3 );

If you want to query the method name, you can use help ()

> DB. Help ()

> DB. Whatever. Help ()

If the parameter table is ignored, the source code is output.

> Printjson

Function (x ){

Print (tojson (x ));

}

Since Mongo is a completely JavaScript shell, it supports any JavaScript function, syntax, and class.

You can also define your own classes and global variables (such as DB ),

For the API list, see

Http://api.mongodb.org/js/

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.