MongoDB Database Basic Operations

Source: Internet
Author: User
Tags mongodb server mongodb version

In order to save the user data and business data for a site, a database is usually required. MongoDB and node. JS are particularly well-matched because MongoDB is a document-based, non-relational database that is stored in Bson (the lightweight binary format of JSON), and the commands for managing databases such as additions and deletions are much like the JavaScript syntax. This article describes the MongoDB database in detail


Database, as the name implies, is the warehouse of data storage, the main functions have two

1. Storing data in an organized manner

Unlike storing files on disk, the database organizes the data storage for the user, and the user simply writes the data according to the interface provided by the database, and the data is stored in a standard format.

2, according to different needs of the query

The database can not only write data, but also support data query, and can be queried according to different requirements. Because storage is organized, queries can be more normalized and queries are much faster

The difference between different databases is that the organization of the data is different, and different kinds of queries are provided. Users can choose the right database according to their needs.


There are many kinds of database classification, according to the support of SQL language, can be divided into the following two kinds:

1, SQL database, such as Oracle, MySQL, etc.

2. NoSQL databases, such as Redis, MongoDB, etc.

With the advent of Internet applications in scale, the traditional SQL database has encountered some design drawbacks. For example, SQL-to-table definitions make the application inflexible and scale-out more difficult. Rather than some features that are difficult to meet, many of the features of SQL database are not useful. For example, in many scenarios, timely access is not necessary, and there is no particular transaction requirement, and these additional features consume the performance of SQL database

So NoSQL databases came into being, and the NoSQL name was not just SQL, meaning "more than SQL". In fact, most NoSQL databases give up support for the SQL language. NoSQL non-relational databases mostly give up some of the features compared to SQL-relational databases. For example, give up real-time consistency, complete support for transactions, and multiple table queries. It sounds a lot of drawbacks, but the benefits are obvious, NoSQL databases are simple, convenient, scalable, and have better performance.


MongoDB is an open source NoSQL database, known in the country as the Mango database. Linux, Apache, MySQL, and PHP make up a very famous lamp architecture. Now, it is proposed to replace MySQL, which represents m in lamp, with MongoDB

There are many NoSQL databases, why should you choose MongoDB?

MongoDB is a database based on distributed file storage. Written in the C + + language, designed to provide scalable, high-performance data storage solutions for WEB applications. MongoDB uses collections (collection) and documents to describe and store data, a collection (collection) is equivalent to a table, a document is equivalent to a row, a field is equivalent to a column, not a relational database like MySQL, Table structure is fixed, such as a row consists of a number of columns, row rows are the same, and MongoDB different, a collection of multiple documents can have different structure, more flexible

MongoDB has its own distinctive features, summed up the following 4 articles

1. No constraint on table structure

In a traditional SQL database, you need to define the table structure for each table. If you have new storage requirements, you often need to add new fields and change the table structure. In some scenarios, it can be inconvenient, and for MongoDB, this is no longer a problem. Because it does not have the concept of a table structure, there is no need to initialize this table before using a single table. This feature of MongoDB is appropriate for fast development and changing business requirements.

2. Full index support

Some NoSQL databases, such as Redis, are memory databases and are fast. However, as a key-value database, only one type of keystroke query is supported. Flexibility, scope, and ease of use are all impacted, such as HBase, which is fast to write. However, the same query is limited, it only supports single-index, two-level indexes need to implement their own

MongoDB supports single-touch indexing, multi-key indexing, full-text indexing, and geo-indexing. So MongoDB is a very well-functioning NoSQL database, also known as a non-relational database closest to a relational database

3. Good data security and convenient scale expansion

MongoDB uses replica sets for long copy storage to ensure data security. At the same time, MongoDB's built-in sharding technology makes it easy to scale data. Shard Technology is a very novel feature, it contains automatic data interface, dynamic expansion and contraction of a series of other databases need a lot of manual work, while providing a unified access to the database portal, no need to be distributed at the application layer, significantly reduce labor costs

4. Complete documentation support and driver support


First, select the appropriate MongoDB version on the download page of the website to download

Then, step by step to install

By default, installed in the MongoDB folder under the Program Files folder of the C drive

Server Configuration

"Build Server"

The following steps are required to build the server

1. Create Data folder to store the database file, create log folder to store database, create Bin folder to store database executable file, create Conf folder to store database configuration file

2, you need to set environment variables under Windows system, otherwise the command line will prompt the Mongod command is not available

In the path of the environment variable, add the directory for the Mongod.exe file

3. Next, there are two ways to start the MongoDB service, one of which is to set the Dppath parameter value to a custom directory path, as shown below


The default port for MongoDB is 27017, as seen by

4, another is the Conf folder under the new mongod.conf file, in this file will set the MongoDB boot configuration parameters

DBPath = Dat\nlogpath = Log/mongod.log

Mongod-f conf/mongod.conf

This method does not prompt in the command-line tool because the record is saved to the log file, and the MongoDB service is turned on normally

"Connect to Server"

After the MongoDB server is set up, you need to connect using client MONGO to do the next step.

Because you are using MONGO to connect to the MongoDB server, you need to ensure that the command line tool that starts the MongoDB server is not closed, a new command line tool is opened, and the name of the database is entered MONGO,test

First switch to the admin database (use admin) and then close the service using the Db.shutdownserver command

Database operations


The default database in MongoDB is test, and if no new database is created, the collection will be stored in the test database


Use show DBS to view the database

Show DBS


Using the use command to switch/create the database, you will find that the database you created is not in the list of databases, and you need to insert some data into the database to display it.

Use Db_name

"Show Current Database"

Use the DB command to display the current database


"Write data to the collection"

Use the DB. Collection name. Insert (document) to write the document's data to the collection, which is formatted as JSON. All data stored in the collection is in the Bson format. Bson is a binary form of a class JSON storage format, referred to as binary JSON.


"View Collection"

The above insert operation automatically creates the collection Db1_coll1, using the show Collections command to view all the collections in the current database

"Delete Database"

This will delete the currently selected database. If no database is selected, it will delete the default ' test ' database


Collection operations

Collections are similar to data tables in SQL databases and are identified as collection

You can use the command show collections to check the created collection

[note] You can also use show tables to view the collection

"Create Collection"

When you insert a document, MongoDB first checks the size of the upper bound collection capped field, and then checks the Max field

Db.createcollection (name, {capped: <boolean>, Autoindexid: <boolean>, size: <number>, Max <number })

Name: Collection of names

Capped: Whether to enable the collection limit, if you need to set a constraint, default is not enabled, this parameter does not make sense

Max: Limit of maximum number of bars in the collection, defaults to No limit

Size: Limits the amount of space used by the collection, and defaults to No limit, and the size has a higher priority than max

AUTOINDEXID: Whether to use _id as the index, by default (TRUE or FALSE)

[note] When inserting a document into the collection, the collection is automatically created if the collection does not exist

"Delete Collection"

MongoDB's db.collection_name.drop is used to remove collections from the database. If the selected collection is deleted successfully, the Drop method returns True, otherwise false

MongoDB Database Basic Operations

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: 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.