MongoDB Basic Database Operations Tutorial

Source: Internet
Author: User
Tags findone mongodb mongodb query

0. Target
Be familiar with some basic operations of MongoDB on the command line, and prepare for the next node.js operation MongoDB.
If you have ever studied or contacted a relational database (such as MySQL, SQL Server, etc.), then when reading this article, you can do the following:
Table (table)-> Collection (set)
Log (record)-> document (documentation)
Of course, this correspondence is not accurate, because the structure of table (table) is fixed, and collection (set) is not, log (record) of "Row", and document (documents) structure is more diverse. But for beginners, such metaphors can be used more quickly; in fact, the structure and operation of the document database MongoDB is similar to that of relational databases such as MySQL.
If you have never studied the database, then suggest you first look at the opening article introduced the book "MongoDB authoritative Guide", as well as the reference book "NoSQL Database Technology Combat", first on the concept of the non-relational database has an understanding, then look at this article.
If you have studied MongoDB database, then the right to review, if there are errors, please correct me. If you are already a great God, then you are more welcome to your guidance.
1. Connecting to the database
Before you connect to the database, verify that the MongoDB service is turned on. Please refer to the previous section for details.
Open the command line in the MongoDB directory, enter Mongodb\bin, and type the command MONGO
The code is as follows Copy Code
C:\mongodb\bin>mongo

Enter MongoDB
2. Switch databases
The default shell is connected to the localhost test library for this computer, as you can see in the picture above that the database currently in use (Connecting to:) is "test"
If you want to switch the database, you can enter the following command
The code is as follows Copy Code
Use MyDB
The mydb above is the name of the database to switch
3. Insert a record
Switch to Database Myfirstdb
The code is as follows Copy Code
Use Myfirstdb

switching databases
Create object A,b and save them separately
The code is as follows Copy Code
Create Object A,b
A = {name: "user1"};
b = {name: "User2"};
Save Object A,b
Db.user.save (a);
Db.user.save (b);

Execution results
Viewing results with visual tools

Mongocola View Results
Notice that we didn't create a database named Myfirstdb before, and we didn't create a collection called user, but why is the command still able to execute and get the results we expected? This is because MongoDB, as a document-type database , is a database without a table structure, and it does not need to define a table structure beforehand.
It is this feature that MongoDB has faster processing speed than relational databases, and it also reduces the overhead required to add table structure changes such as fields. In this way, we don't have to care about the consistency between the table structure and the program; In short, it is when you add a field to a program that you do not have to consider whether the database has this field, because MongoDB will automatically create it for you.
4. Insert a record that is a little more complex
The code is as follows Copy Code
c = {name: "User2", Card: "KK8566"};
Db.user.save (c);
Here, we added a field "card" that didn't exist before, so what about the implementation?
Look at the console first.
And look at visual management tools

Mongocola View Results
A card field has been generated automatically.
5. Modify the Record
In the previous example, we saw two "User2", and now we're going to change the last one to "User3."
The code is as follows Copy Code
Db.user.update ({name: "User2", Card: "KK8566"}, {$set: {name: ' User3 ', Card: "KK8566"});
Modify Result:

Modify Results

Mongocola View Results
6. Delete records
We delete the first document
The code is as follows Copy Code
Db.user.remove ({name: "user1"})

Delete

Mongocola View Results
7. Query Records
List all records
The code is as follows Copy Code
Db.user.find ();
As you can see, there are only two documents left in the database for the delete command we executed in the previous section.
Use while to output
The code is as follows Copy Code
var cursor = Db.user.find ();
while (Cursor.hasnext ()) Printjson (Cursor.next ());

Bulk output through while
Convert to Array
The code is as follows Copy Code
var arr = Db.user.find (). ToArray ();
ARR[1]; Display a 1th

Array
In fact, we use a similar approach when we operate MongoDB on the Node.js server side.
8. Condition Inquiry
Using MONGODB query statement to implement MySQL conditional query statement: SELECT * from user WHERE name= "User3"
The code is as follows Copy Code
Db.user.find ({name: "User3"}). ForEach (Printjson);

Conditional query
The above command returns all documents that meet the criteria, and to save costs, you can use FindOne () to get the first document that satisfies the criteria:
The code is as follows Copy Code
Db.user.findOne ({name: "User3"});
Note that this is just a simple condition limit. We have a lot of complex requirements in practical applications, and in MySQL we use multiple and or or to represent relationships with and OR. In MongoDB, there are also keywords similar to and OR or, but in MongoDB, everything is expressed in a JSON-like format. The specific operation I will do in the following article detailed introduction, Welcome to read.
The code is as follows Copy Code
9. Limit the number of result sets
Add limit (num) after the query statement
The code is as follows Copy Code
Db.user.find (). limit (3); Limit to 3 documents

at this point, there are so many mongodb operations, and there are more advanced operations that will be listed in subsequent articles
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.