MongoDB Getting Started Tutorial (ii)

Source: Internet
Author: User
Tags clear screen mongodb collection unique id mongodb support

In the previous blog post, I described in detail from MongoDB Introduction to installation, in this section, mainly from the overall perspective to see MongoDB.

MongoDB's Data architecture

That's what the official describes.
MongoDB stores all documents in collections. A collection is a group of related documents that has a set of shared common indexes. Collections is analogous to a table in relational databases.

According to its description, the results of MongoDB can be broadly summarized as:

Parsing: A database can contain multiple collections (colection), each of which can contain multiple documents. Can be analogous, SQL database, a database contains multiple tables, each table contains multiple records.

Command Specification Database commands

1. Any UTF-8 (Chinese is OK)
2. Cannot be an empty string
3. Must not contain: ' Space ', '. ', ' $ ', '/', ' \ ', '/'.
4. The length must not exceed 64 bytes.
5. Cannot use reserved word: admin, local, config

Collection

1. Arbitrary UTF-8 string
2. Cannot be an empty string
3. Cannot contain \ t, $
4. Cannot start with system.

Document

1. Arbitrary UTF-8 string
2. Cannot be an empty string
3. Cannot contain \ t, $
4. Cannot start with _

Data type

The official tips for MongoDB support types are as follows:

NULLNull is used to represent a null value or a field that does not exist. {"Tmpkey": null}
BooleanThe Boolean type has two values of ' true ' and ' false1 '. {"Tmpkey": true}
32-bit integerType is not available. JavaScript only supports 64-bit floating-point numbers, so 32-bit integers are automatically converted.
64-bit integerThis type is not supported. The shell uses a special inline document to display a 64-bit integer
64-bit floating point numberThe numbers in the shell are all of this type. The following representations are floating-point numbers: {"Tmpkey": 5.12}
stringUTF-8 strings can be represented as string types of data: {"Tmpkey": "ABF"}
symbolsThis type is not supported. The shell converts the symbol types in the database into strings.
Object IDThe object ID is a unique ID of 12 bytes of the document, {"Tmpkey": ObjectId ()}
DateThe date type stores the number of milliseconds that start from the standard era. Do not store time zone: {"Tmpkey": New Date ()}
Regular ExpressionsThe document can contain regular expressions, using JavaScript's regular expression syntax: {"Tmpkey":/\w/i}
CodeThe document can also contain JavaScript code: {"Tmpkey": function () {/* * ...}}
Binary DataBinary data can be made up of strings of arbitrary bytes. However, the shell cannot be used.
Maximum ValueBson includes a special type that represents the maximum possible value. There is no such type in the shell.
Minimum ValueBson includes a special type that represents the minimum possible value. There is no such type in the shell.
Not definedUndefined type can also be used in documents: {"Tmpkey": undefined}
ArrayA collection of values or a list can represent an array: {"Tmpkey": ["a", "B", "C"]}
Inline DocumentThe document can contain other documents, or it can be embedded as values in the parent document, and the data can be organized more naturally without having to be in a flat structure: {"Tmpkey": {"" Color ":" Yello "}}

Operation of the MongoDB collection

When learning about MongoDB collections, you can compare them to tables in SQL database.

Create a Collection

1. Show Create
Before creating, we first set up a database, about the establishment of the database, you can refer to the previous article (http://blog.csdn.net/hsd2012/article/details/51279472)

We know that in SQL database, we use show tables to view the included tables, so how can mongodb see the collections contained in the current database? The show collections is used at this time;

Student represents the collection, and System.indexes represents the index of MongoDB.
2. Implicitly-Created
Db.class.insert ({' ClassID ': 1, ' className ': "Three-year Class two"});
Inserts a document on behalf of the Net class collection (class Number 1, class name is three years, second Class). The essence is that if you insert a piece of data into a collection, MongoDB will automatically help us create the collection if it doesn't exist.

Show all collections in the database

The following two commands are all implemented to display all collections.
Show collections
Show tables

Delete Collection

Db.collectionName.drop ();

Operation of the MongoDB document

When you are learning MongoDB documents, you can compare them to data in SQL database tables. Each row in a database table can be likened to each document in the collection.

Insertion of data

Data insertion in MongoDB refers to the document that is being created, inserted into the specified collection.
The command is as follows:
Db.collectionName.insert (DOC);
Official Documentation Tips:
The operation would create the collection if the collection does not currently exist
Insert a document into a collection
Insert an Array of Documents
If the collection does not exist, the collection is created. Doc can be a collection or an array of collections.
1. Insert a document into the student collection of the school database.

db.student.insert({"stu_id":1,"stu_name":"张三","age":6,"class_id":1});


by Db.student.find (); Find the data in the collection, we can see the data that we just inserted. So what does "_id" mean? This is a globally unique primary key that MongoDB automatically generates to differentiate documents. It consists of four parts: timestamp, machine, PID (process number), counter.
1. Insert multiple documents into the student collection of the school database.

var docArr=[{"stu_id":2,"stu_name":"李四"},{"stu_id":3,"stu_name":"王五","class_id":1},{"stu_id":4,"stu_name":"赵六",age:10,"hobby":"football"}];db.student.insert(docArr);

The code performs the following effects:

Data deletion

The command is as follows:
Db.collectionName.remove (Where,[justone]);
Where represents the delete condition, where {} represents the deletion of all documents.
Justone is false by default, and all matching documents are deleted when there are multiple documents that represent matching criteria. If set to TRUE or 1 (an integer other than 0 can also be set), the delegate simply deletes a document.
Instance
1. Delete the school database student the name (Stu_name) in the collection for the Zhao Liu document.

db.student.remove({"stu_name":"赵六"});

The code performs the following effects:

2. Delete the school database student collection where the class number (CLASS_ID) is a 1.
For ease of operation, I first added some documents to the student collection, at this time the collection of Chinese file data content as follows:

It can be found that there are 4 sets of class_id for 1.

db.student.remove({"class_id":1},2);

The results of the implementation are as follows:

It can be found that although there are many documents that meet the criteria, only one of the documents is deleted.

Data modification

Modifying the data (document) in MongoDB is accomplished by the following command
db.collectionName.update (query,update,upset,multi);
CollectionName: Collection Name
Query: Modified condition, like the WHERE statement of SQL.
Update: Update command, SQL-like SET statement.
upset: optional, default is False, if no data content is found that matches the update criteria, whether to perform an insert operation, 1 or True to insert 0 or false to not insert.
Multi: Optional, MongoDB default is False. Whether to make multi-line updates. 1 or true to make multiline update 0 or false without multi-line updates.
AboutUpdateThere are two forms of format
1. Direct assignment Using { set:{}}
such as { set:{"name": "Zhang San"}, change the name to Zhang San
2. Perform arithmetic operations using {inc:{}}
such as { inc:{"Age": 3}, increase age by 3
{$inc: {"Age":-3}}, minus 3
Instance
1. Update the student number (STU_ID) to 2 document, add a field for it age is 13

db.student.update({"stu_id":2},{$set:{"age":13}});

The results of the implementation are as follows:

2. Update students to set their age to 12

db.student.update({},{$set:{"age":12}},0,1);


3. Increase the age of 1 for all students with class number 2
The code is as follows

db.student.update({"class_id":2},{$inc:{"age":1}},0,1);

Execution effects such as

Basic query operations for data queries

1. Querying all documents in a collection
Db.collectionName.find ();
Example: Find all the data in the collection student.
To make it easier to find, first insert some data into it

for(var i=0;i<20;i++){db.student.insert({"stu_id":9+i,"stu_name":"赵"+i});}db.student.find();

Execution results are as follows

2. Querying the first document in a collection
Db.collectionName.findOne ();

Conditional query

Query criteria in 1.MongoDB

Data Query Criteria in MongoDB application examples to explain
equals (=) ---- Find all students whose name is John Doe Db.student.find ({"Name": "John Doe"});
Equals (! =) $ne Find all students whose name is John Doedb.student.find({"name":{$ne:"李四"}});
Greater than (>) $gt Find all students older than 5db.student.find({"age":{$gt:5}});
Greater Than (<) $lt Find students of all ages less than 15db.student.find({"age":{$lt:15}});
Greater than or equal to (>=) $gte Find all students older than or equal to 5db.student.find({"age":{$gte:5}});
Less than or equal (>=) $lte Find all students younger than or equal to 15db.student.find({"age":{$lte:15}});
With (and) ---- Find all students aged less than or equal to 15 with class number 1db.student.find({"age":{$lte:15},"class_id":1});
or (OR) {$or:[{条件1},{条件2}]} Find all students with age less than or equal to 15 or class 1db.student.find({$or:[{"age":{$lte:15}},{"class_id":1}]});
Non-or (NOR) {$nor:[{条件1},{条件2}]} Condition 1 cannot be satisfied and condition 2 cannot be satisfied.
Set operator (in) {$in Find students of age 12 or 13 or 14.db.student.find({"age":{$in:[12,13,14]}});
Set operator (All) {$all Find hobbies including football, and basketball all studentsdb.student.find({"hobby":{$all:["football","basketBall"]}});
is present (exists) {$exists Query for all students with Hooby db.student.find({hobby:{$exists:1}}) , {$exists: 0} means not present
Statistics, sorting, paging

1. Statistics
Db.collectionName.count ();
Db.collectionName.find (). Count ();

2. Sorting
Db.collectionName.find (). Sort ({key:1});//key in ascending order

Db.collectionName.find (). Sort ({key:-1});//key descending order

3. Paging
Db.collectionName.find (). Skip (n). Limit (m);
Parsing: Starting from the nth document in CollectionName to read the M documents, it is important to note that in MongoDB, N is starting from 0. Can be analogous to the limit method in MySQL. N equals the first method in limit, M equals the second argument in limit
When using paging, if you use count, be aware that the MongoDB statistic number defaults to ignore paging, see:

How to make it do not neglect paging? At this point, you need to pass a parameter count (flag) to count. Flag 0 (by default, 0) ignores paging, flag is 1, and paging is not ignored.

Instance:
1. Remove 6~12 data from the student

db.student.find().skip(6).limit(6);


2. Remove the first data from the collection student

db.student.find().skip(0).limit(1);

Projection Query

In MongoDB, the above-mentioned every query is all the keys are displayed, how to just let some key display it? This will use the projection query.
For example, I only let the collection student in the query results stu_name display.

db.student.find({},{_id:0,stu_id:0});


Parsing: In MongoDB, the second parameter inside the Find function is used to control which keys are displayed or not displayed. 0 is not displayed, 1 is displayed. By default, it is displayed.

Note

Clear Screen
CLS command

MongoDB Getting Started Tutorial (ii)

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.