MongoDB Getting Started notes

Source: Internet
Author: User
Tags data structures install mongodb mongodb download string format mongochef

MongoDB, as the first database in NoSQL, has been using more and more people in recent years, and as a developer, it is necessary to understand the next MongoDB database. The following will give you the basic knowledge of the MongoDB database, there is no place to welcome correct, qq:1416759661. Also welcome everyone plus QQ Group 7835003 joint discussion.

If you feel this article is difficult to understand, we also have relevant video tutorial http://www.yyjcw.com/list.html

1 Basic Concepts 1.1 What is a database

The database is a warehouse that organizes, stores, and manages data according to its structure, which is generated more than 60 years ago, with the development of information technology and market, especially after the 1990s, the database technology has been developed more rapidly and applied more widely. It is mainly used to manage the data of various systems as an important technical means for scientific research and decision-making.

1.2 Common databases

Relational database: Access MYSQL SQL Server Oracle DB2, etc.

Non-relational database: Mongodb,redis,hbase,couchdb,sqlite and so on.

1.3 NoSQL Introduction

NoSQL (NoSQL = not-only sql), meaning "not just sql", refers to non-relational databases.

With the rise of internet web2.0 website, the traditional relational database in coping with web2.0 website, especially the web2.0 pure dynamic website of ultra-large-scale and high-concurrency SNS type, has been unable to overcome, exposing a lot of difficult problems, and the non-relational database has been developed very rapidly because of its own characteristics. NoSQL databases are created to address the challenges of multiple data types in large-scale data sets, especially big data application challenges.

1.4 MongoDB Introduction

MongoDB is a database based on distributed file storage. Written by the C + + language. Designed to provide scalable, high-performance data storage solutions for WEB applications. MongoDB is the most versatile non-relational database, most like relational database.

2 Preparation 2.1 MongoDB download and install

MongoDB website Address:

https://www.mongodb.com/

Mongodb:

Https://www.mongodb.com/download-center#community

MongoDB for Windows 64-bit is suitable for 64-bit Windows Server R2, Windows 7, and the latest version of the Window system.

MongoDB for Windows 32-bit is suitable for 32-bit Window systems and the latest Windows Vista. MongoDB databases on 32-bit systems have a maximum of 2GB.

Select the appropriate version for your system to download:

Download the 32-bit or 64-bit. msi file based on your system, double-click the file after downloading, and install it as prompted.

2.2 Mongochef Installation

Mongochef can improve your use of MongoDB's happiness index, he is MongoDB's visual interface management tool.

2.3 Setting Environment variables

Setting environment variables under Win7: QQ 1416759661

The first step: Right-click on My Computer, select Properties

Step Two: Locate and open advanced system configuration.

On the next page, click Advanced System Configuration to open the System Properties window.

Step three: Find the "Environment variables" button and click.

Fourth: In the Environment Variables window there are generally two variables, one is the user-specific environment variable you are currently using, and the other is a system variable that all users can access. In fact, if you only use one user on your computer, then no matter whether you modify the user's environment variables or system variables, the effect is the same. To prevent new users from being created in the future, I recommend that you modify the system variables instead of the environment variables that are unique to a user.

Add a semicolon at the end of the variable value; C:\Program Files\mongodb\server\3.2\bin

and then save.

2.4 Creating a Folder

We previously installed the data management software, through the database management software can build a lot of database files, we are going to put the new database file where? You need to specify a location.

The relationship between MONGODB database management software and database files is like the relationship between Office software and Word documents.

1. Set up a folder in the D disk MongoDB, and set up subdirectories db and log.

D:\mongodb\db, D:\mongodb\log, respectively, for storing database files and database log files.

2. Remove the read-only attribute from the MongoDB folder.

2.5 Start MongoDB To install it as a Windows service

Run as Administrator Cmd.exe , Enter the DOS command interface and execute the following command

Mongod--dbpath "d:\mongodb\db"--logpath "D:\mongodb\log\MongoDB.log" –logappend--install--servicename "MongoDB"

Mongod.exe--remove--servicename "MongoDB"

When Mongod.exe is closed, Mongo.exe cannot connect to the database, so it is troublesome to open the Mongod.exe program every time you want to use the MongoDB database, so we can install MongoDB as a Windows service

Run as Administrator cmd, go to the Bin folder and execute the following command

Mongod--dbpath "d:\mongodb\db"--logpath "D:\mongodb\log\MongoDB.log"--install--servicename "MongoDB"

Here MongoDB.log is the log file that was started,--servicename the "MongoDB" service named MongoDB

Then start the MongoDB service

> NET START MongoDB

Open Task Manager and you can see that the process has started.

Test connection

> MONGO

2.6 Closing the service

First CTRL + C

Close service: net stop MongoDB

3 MongoDB Basic App 3.1 common commands

> Help View assistance

Show Database list > show DBS

Create DATABASE > Use dbname

If the database does not exist, create the database dbname, or switch to the specified database dbname. The database created is not in the list of databases, to display it, we need to insert some data into the database dbname

The default database in MongoDB is test, and if you do not create a new database, the collection will be stored in the test database.

Show collections in a database show collections

3.2 Adding data

Db.web.save ({"Name": "Lao Li"}) created a collection called Web and added a new {"name": " Lao li "} of Data

Db.web.insert ({"Name": "Ghost", "Age": ten}) inserts a new data into the Web collection, if there is no Web This collection, MongoDB will automatically create

There is a slight difference between save () and insert (): If the new data primary key already exists, insert () will not do the operation and prompt the error, while save () changes the original content to new content.

_ID is the primary key, which is a unique identifier for each piece of data, and cannot be duplicated, just as the ID is the only number for each person.

Existing data: {_id:objectid ("57E8D34B4764FB71D0A89CAA"), "name": "Lao Li"}, _id is the primary key

Insert ({_id:objectid ("57E8D34B4764FB71D0A89CAA"), "name": "Lao Wang"}) will prompt for errors

Save (ObjectId ("57E8D34B4764FB71D0A89CAA"), "name": "Lao Wang"}) will change "Lao Li" to " old King ", has the function of update.

3.3 Deleting data

1. Deleting documents

2. Deleting a collection

3. Delete Database

    • Db.users.remove ({}) delete All data under the Users collection
    • Db.users.remove ({"Name": "LECAF"}) deletes data name= "LECAF" under the users collection
    • Db.users.drop () or Db.runcommand ({"Drop", "users"}) Delete collection users
    • Db.runcommand ({"Dropdatabase": 1}) Delete the current database, note that 1 here does not have double quotes.
    • Db.users.find () find All data in the Users collection
    • Db.users.findOne () to find The first data in the users Collection
    • Db.web.update ({"name": "A1"}, {"sex": 1}) modify name=a1 's data to sex=1 , the first parameter is the lookup condition , the second parameter is the modified content , the primary key cannot be modified ,
3.4 Finding data 3.5 modifying data 3.6 MongoDB Advanced application 3.6.1 Condition Lookup

The meaning of learning commands is: When we do the system, the backend personnel need to provide data to the front-end developers, if the backend staff with visual tools, but his own eyes can see, but if you want to provide this data to the front end, he needs to use code to check the database, the results of the query back to the front.

To this end: the teacher to everyone to organize the following these common query examples, if you forget later, turn out to see.

In advance of a singer's JSON data, we can import him into the database, practice to find commands.

Syntax 1:db.collection.find ({"Key": Value}) finds data for Key=value.

Example 1: Find a female singer.

Idea: Find the singer who sex= "female".

Specific commands:

Syntax 2:db.collection.find ({"key": {$gt: Value}}) key > value

Example 2: Find a singer older than 53.

Syntax 3:db.collection.find ({"key": {$lt: Value}}) key < value

Example 3: Search for singers younger than 35 years old.

Syntax 4:db.collection.find ({"key": {$gte: Value}}) key >= value

Example 4: A singer with a score greater than or equal to 95 is queried.

Syntax 5:db.collection.find ({"key": {$lte: Value}}) key <= value

Example 5: Search for singers who are younger than or equal to 32 years old.

Syntax 6:db.collection.find ({"key": {$gt: value1, $lt: value2}}) value1 < key <value2

Example 6: Find a singer between 30-40 years of age.

Syntax 7:db.collection.find ({"key": {$ne: Value}}) key <> value

Example 7: Query foreign singers.

Analysis: The condition is country not equal to "China"

Syntax 8:db.collection.find ({"key": {$mod: [10, 1]}) modulo operation, equal to key% 10 = = 1 i.e. key divided by 10 + 1

Example 8: Query score of 5, 15, 、。。。。 95 of the singers.

The syntax 9:db.collection.find ({"key": {$in: [1, 2, 3]}) belongs to any of the conditions equal to the key equal to [1, 2, 3].

Example 9: A pop star with an ordinal number (num) of 3 or 6 or 9.

Syntax 10:db.collection.find ({"key": {$nin: [1, 2, 3]}) does not belong, the condition equals the value of key does not belong to either [1, 2, 3].

Example 10: Query A singer whose nationality is not American or Korean.

Syntax 11:db.collection.find ({"key": {$size: 1}}) $size number, size, condition equal to the number of values corresponding to key is 1 (the value must be an array)

This is a bit difficult to understand, easy to understand through examples:

Each singer has a masterpiece, and the masterpiece is an array.

Example 11: Query for 3 singers representing the works.

Syntax 12:db.collection.find ({"key": {$exists: True|false}})

$exists field exists, true returns data with field key present, FALSE returns data without field key

Example 12-1: Query the data that contains the Tel field.

Before the data fields are the same, insert a data {"name": "Test", "tel": "15388889999"}

Then query:

Example 12-2: Querying for data that does not contain a tel field

Syntax 13:db.collection.find ({$or: [{a:1}, {b:2}]})

Data that meets any of the two criteria. $or the meaning of a grammar or expression. (Note: After MongoDB 1.5.3 version is available), the data matching the criteria A=1 or qualifying b=2 will be queried.

Example 13: An entertainment company 15 people, the data are in the database, an activity must be Andy Lau to attend, in addition to the team of all the female singers to cooperate with the performance, the leader arranges you to help print the singer's information.

Db.collection.find ({"Key.subkey": Value}) the values in the inline object match, note: "Key.subkey" must be quoted.

Example 14: Inserting a test data

Db.singer.insert ({"Name": "Test2", score:{"yy": +, "SX": +, "WY": 95})

The score corresponding value of this data is an object.

Example 14: Query the language score of 80 students.

3.6.2 Sort

Db.collection.find (). Sort ({"Key1":-1, "Key2": 1}) Here the 1 stands for ascending,-1 for descending

Example 1: Sort All Star Ann ages.

Example 2: Sort all singers in descending order of age and then in descending order by Num field.

NOTE: num in JSON data is of type string.

3.6.3 Index

Indexes can often greatly improve the efficiency of queries, and if there is no index, MongoDB must scan every file in the collection and select those records that meet the query criteria when reading the data.

This scan full set of query efficiency is very low, especially in the processing of large amounts of data, the query can take dozens of seconds or even a few minutes, which is very fatal to the performance of the site.

Indexes are special data structures that are stored in an easy-to-traverse collection of data that is a structure for sorting the values of one or more columns in a database table

For example: We query Li Yuchun when db.singer.find ({"name": "Li Yuchun"})

If the name field is not indexed, the database will scan all of the data at query time, if the data volume is small, it does not feel slow, when the data more and more time, it will be more and more slow.

This time, if you create an index for name, the query speed will be faster.

MongoDB uses the Ensureindex () method to create an index.

The basic syntax format for the Ensureindex () method is as follows:

>db. Collection_name.ensureindex ({key:1})

Establish an index for the name field as follows:

The visualization tool can see the index you just created:

The Key value in the syntax is the index field you want to create, 1 for the specified index in ascending order, or 1 if you want to create the index in descending order.

Instance

>db.col.ensureindex ({"title": 1}) >

In the Ensureindex () method, you can also set up to create indexes using multiple fields (called Composite indexes in relational databases).

> Db.col.ensureIndex ({"title": 1, "description":-1})

3.6.4 Other

Db.collection.find (). Limit (5) controls the number of returned results, and if the argument is 0, the limit () will not work if it is not constrained

Db.collection.find (). Skip (5) controls how much the returned result skips, and if the argument is 0, then skip () will not work, or skip 0

Db.collection.find (). Skip (5). Limit (5) can be used for paging, skipping 5 data and then fetching 5 data

Db.collection.find (). Count (True) count () returns the number of result set bars

Db.collection.find (). Skip (5). Limit (5). Count (True) to obtain the actual number of results returned when adding skip () and limit (), a parameter of true is required. Otherwise, the total number of results that match the query criteria is returned

Fuzzy query:

Db.collection.find ({"Name":/ab/})

The above is a common query, if the work encountered more complex requirements, you can check the document to solve.

3.7 Using Visual Tools

4 Mongoose4.1 Mongoose Introduction

Mongoose Library in short, a convenient package for manipulating MongoDB databases in the node environment, an object model tool that mongoose data from a database into JavaScript objects for you to use in your app.

Official Document: Https://www.npmjs.com/package/mongoose

Premise: Install Nodejs and MongoDB

4.2 Mongoose Operation Flow 4.2.1 installation Mongoose

NPM Install Mongoose

4.2.2 Connection Database

The prerequisites for connecting to a database using Mongoose are:

1, MONGO database has been run.

2, has installed the Mongoose package

var mongoose = require ("Mongoose");

Mongoose. Promise = global. Promise;//Configure Mongoose 's Promise.

The connection string format is mongodb://host/database name

Mongoose.connect (' mongodb://localhost/student');


The above sentence means connecting to the local MongoDB student database .

Extended:

Mongoose. Promise = global. Promise;

Connect local mongodb, native IP 127.0.0.1, port: 27017 database: Student
Mongoose. Connect ("Mongodb://127.0.0.1:27017/student",function(err) {
if (!err) {// If the connection is successful, print out connected to Mongodb
console. log ("connected to Mongodb");
}Else{
Err // throws an exception if the connection fails
}
});

4.2.3 New Data

Let's start by explaining a concept Schema:

It can be understood as a database model skeleton, can be regarded as a mold in the factory, like a teacup, water is the final function of the Cup, the Cup itself is like model, then the cup production is to rely on the factory mold molding. Schema not only defines the structure and performance of the document , but can also include extensions, instance methods, static methods, composite indexes, and document life cycle hooks.

Stored data steps: Define schema-(pattern) > Create model-(Model) > Instantiate method.

Mongoose. Schema;
//
var student Schema 
name: String,
Age: String
});

Student Schema What types are:

// through Mode Student  Create a model student
Mongoose. Model ("Students",student);
Studentquerymodel Mongoose. Model ("Students"); // the model for querying
// through the model  Write Data
Instance1. name= "YYJCW";
Instance1. age = "18";
// save by using the Save method
Instance1.save (function(err) {
(ERR) {
console. log (' save failed '
return;
}
});
4.2.4 Deleting data

Ideas:

1, delete the data first to know which piece of information to delete, you need to know the ID of the information.

2, the corresponding ID data query out, execute the Remove method

If we want to delete the data of id= "57e24521a755e1154039a403".

var id= "57e24521a755e1154039a403";

Studentquerymodel. FindByID (ID,function(err,doc) {
if (!doc) {
Next (NotFound ("Doc not Found"))
}Else{
Doc.remove (function() {
console. log (' Delete succeeded ');
})
}
});

4.2.5 Modifying data

The idea of modifying the data: First query the corresponding ID data, re-assign the fields that need to be modified, and then execute Save method.

If we want to modify the data of id= "57e24521a755e1154039a403".

var id= "57e24521a755e1154039a403";

Studentquerymodel. FindByID (ID,function(err,doc) {
Console.log (DOC);
Doc.name= "XIAOYYJCW";//change name to XIAOYYJCW
Doc.save(function(err) {
if (!err) {
console. log (' modified successfully ');
}Else{
Err
}
});
});
4.2.6 Querying data
The following find the first parameter {} is empty, indicating that all data is queried:
Docs represents a collection of results for the query.
Studentquerymodel. Find ({},function(err,docs) {
Console.log (Docs);
});

MongoDB Getting Started notes

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.