Getting started with MongoDB

Source: Internet
Author: User
Tags mongo shell
Getting started with MongoDBConnect to database

Here, we use the Javascript shell provided by MongoDB for database operations. Of course, we can use different drivers to implement the same function in other programming languages, however, shell is very convenient in database management.

The method for starting JavaScript shell is simple. The command is as follows:

C: \ MongoDB \ bin \ Mongo

By default, shell connects to the local test database and the following information is displayed:

C: \ MongoDB \ bin> Mongo

MongoDB shell version: 2.0.2

Connecting to: Test

>

"Ing to" is followed by the name of the database to be connected. To change to another database, run the following command:

> Use mydb

Switched todbmydb

Note: After the database is switched, if the database to be switched does not exist, the system will not create the database immediately, but will create it only when it is inserted for the first time. This means that when you use the "show DBs" command to view the existing database, you cannot see the switched database.

Dynamic Mode (NO mode)

MongoDB contains databases, collections, and indexes similar to traditional relational databases ). For databases and collections of these objects, the system will implicitly create them. However, once they are created, they will be recorded in the system directory (dB. systems. collections, DB. system. indexes ).

A collection is composed of documents that contain fields, that is, fields in traditional relational databases. However, unlike relational databases, MongoDB does not pre-define the domain or define the mode for the document. This means that different domains and their values in the document can change. Therefore, MongoDB does not
Table operation to increase or decrease the number of fields. In practice, a document usually contains the same type of structure, but this is not necessary. This elasticity makes it easy to change or increase the mode. You can perform the "alter table" operation without having to write any script program. In addition, the dynamic mode mechanism facilitates repeated development of MongoDB-based software, greatly reducing the workload caused by changes in the mode.

Insert data to a collection

Create a set named test and insert data to test. We create two objects J and T and save them to the things set.

In the following example, ">" indicates the Shell Command Prompt:

> J = {name: "mongo "}

{"Name": "mongo "}

> T = {X: 3}

{"X": 3}

> DB. Things. Save (j)

> DB. Things. Save (t)

> DB. Things. Find ()

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

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

>

Note:


We do not have a predefined set. The database automatically creates the set during the First insert operation.

The document we store contains different fields. In this example, the document does not contain the same data element. But in actual
In applications, data of the same structure is often stored in a collection.

Once stored in the database, if not defined in advance, the object will be automatically allocated with an objectid, and
Stored in the field_id field. When you run the above example, there will be different objectid.

Add more records to the collection. The following code uses the loop structure:

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

> DB. Things. Find ()

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

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

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

......

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

Has more

>

It is worth noting that the preceding example does not show all documents. The default number of shell files is 20. To view other documents, run the it command:

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

Has more

> It

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

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

>

Strictly speaking, find () returns a pointer object. But in the above example, we didn't assign the pointer object to any variable. Therefore, shell automatically iterates the pointer until the initial result set is given. We can use the it command to display the remaining information, but we can also directly operate on the pointer returned by find, it will be introduced in section 11.3.3.4.

Query data

Before discussing data query, let's take a look at how to operate the query results, that is, pointer objects. We will use the simple find () method to return all the documents in the set, and then discuss how to write specific query statements.

To understand all the elements in the collection when using Mongo shell, We need to explicitly use the pointer returned by the find () method. Use the while loop to iterate on the pointer returned by find () to implement the same query result as in the previous example:

> Var cursor = dB. Things. Find ()

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

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

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

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

......

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

>

The above example shows the pointer iterator. The hasnext () method determines whether the document can be returned, and the next () method returns the next document. We also use the built-in printjson () method to present documents in JSON format.

When working in Javascript shell, we can also use features of the Javascript language, such as using foreach to output pointer objects. The following code outputs the same query results as above, but uses foreach instead of the while loop in the Code:

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

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

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

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

......

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

>

When using the foreach () method, you must define a function for each document pointed to by the pointer (the built-in method printjson () is used here ()).

In Mongo shell, you can operate the pointer like an array:

> Var cursor = dB. Things. Find ()

> Printjson (cursor [4])

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

>

When a pointer is used in this way, the value indicated by the pointer can be loaded to the memory at the same time, which is not conducive to returning large query results because memory overflow may occur. For queries with large results, the pointer value should be output in iteration mode.

In addition, you can convert the pointer to a real array for processing:

> Arr [5]

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

>

Note that these array features are only applicable to the shell mode, but not for other language environments. MongoDB pointers are not snapshots. When you operate on a set, if another person calls next () for the first or last time in the Set, your pointer may fail to return results, therefore, you must explicitly lock the pointer you want to query.

Conditional Query

We already know how to operate the pointer returned by the query. Now we need to filter the query results based on specific conditions. In general, to implement conditional query, you need to create a "Query document", that is, the document that specifies the mode and value that the key needs to match. For this, the example proves much clearer than the text. In the following example, we will provide SQL queries and explain how to use mongoshell to make MongoDB implement the same query (see table 11-4 and table 11-5 ). This type of conditional query is the basic function of MongoDB, so you can use other program drivers or languages to implement conditional query.

Table 11-4 MongoDB condition query (name = "mongo ")

Select * from things where name = "mongo"

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

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

>

Table 11-5 MongoDB condition query (x = 4)

Select * from things where x = 4

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

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

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

Continue table

......

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

>

The query expression itself is a document, a query document {A: A, B: B ,...} It means "where
A = A and B = B and ...". For more information about conditional queries, go to the MongoDB official website to view the MongoDB developer Manual. The URL is as follows:

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

MongoDB also allows the return of "some documents", that is, the results only contain some sub-elements of the database documents, similar to queries on certain columns in relational databases. To implement this query, you can add the second parameter in the find () method to return certain elements. In order to facilitate the description, we still implement the find ({X: 4}) query, except that additional parameters are added so that the result only contains the J element:

Table 11-6 MongoDB condition query (return specific element J)

Select J from things where x = 4

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

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

......

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

>

Note: The "_ id" field is always returned in the result.

 

Author Profile

Lu jiaheng is a professor at Renmin University of China and a doctoral advisor. In, he graduated from the Department of Computer Science from the National University of Singapore and obtained a doctorate degree. In, he studied postdoctoral studies at the University of California (Irvine) and joined the People's University of China in, in 2012, he was promoted to a professor. The main research fields include database technology and cloud computing technology. He has published more than 40 database papers at major international conferences and journals, such as sigmod, vldb, icde, and www. He has edited many cloud computing and Big Data textbooks and works.

This article is excerpted from the book Big Data Challenges and nosql database technology. Edited by Lu jiaheng, published by the Electronic Industry Publishing House.

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.