Novice Mac from Getting started to giving up MongoDB

Source: Internet
Author: User
Tags brew install mongodb create index install mongodb mongodb query one table

1. 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. A product between a relational database and a non-relational database, which is the most versatile and most like a relational database. The data structure it supports is very loose and is a JSON-like Bson format, so you can store more complex data types. The most important feature of MONGO is that its supported query language is very powerful, its syntax is somewhat similar to object-oriented query language, almost can implement similar relational database single table query of most functions, but also support the indexing of data. If you ask me what MongoDB has to do with MySQL, I say it's like JavaScript and Java.

2. Features

MongoDB's design goals are high performance, scalable, easy to deploy, easy to use, and easy to store data. The main functional features are as follows:

(1) For collection storage, it is easy to store the data of the object type (in MongoDB, the data is grouped in the collection, the collection is similar to a table in an RDBMS, and a collection can store an unlimited number of documents). (2) mode free, with modeless structure storage (the data stored in the collection in MongoDB is a modeless document, and the use of modeless storage data is an important feature of the set that distinguishes the tables in the RDBMS). (3) Full index support, can be indexed on any property, including internal objects (MongoDB Index and RDBMS index is basically the same, you can create indexes on the specified properties, internal objects to improve the speed of the query). (4) Support query (MongoDB supports rich query operations, MongoDB almost supports most queries in SQL). (5) Powerful aggregation tools (MongoDB provides powerful aggregation tools, such as count, group, and so on, in addition to providing rich query functionality, and supports the use of MapReduce to accomplish complex aggregation tasks). (6) Support replication and data recovery (MongoDB supports master-slave replication mechanism, can achieve data backup, failure recovery, read extension and other functions). (7) Use efficient binary data storage, including large objects such as video. With binary format storage, you can save any type of data object. (8) Automatic processing of shards to support the scale of cloud computing (MongoDB supports cluster auto-segmentation data, shard the data to enable the cluster to store more data, to achieve greater load, but also to ensure the load balance of storage). (9) Support for Perl, PHP, Java, C #, JavaScript, Ruby, C, and C + + language drivers (MongoDB provides database driver packages for all current mainstream development languages, and developers can easily become access to the MongoDB database). (10) The file storage format is BSON (an extension of JSON) (BSON is the abbreviation for JSON in binary format, BSON supports the nesting of documents and arrays). (11) can be accessed over the network (MONGODB database can be accessed remotely via the network). 3. Core   The basic core concept in MongoDB is a document, a collection, a database, as shown in the following table:

4. Advantages

    • -High Scalability
    • -Distributed computing
    • -Low cost
    • -Flexible architecture, semi-structured data
    • -Simple and efficient relationship 

5. Disadvantages

    • -No standardization
    • -Limited query function (so far)
    • -Limited safety

6. Installation

Using a brew installation, you can also use the Curl command to download the installation:

Brew Install Mongodb/sudo Brew Install MongoDB

If the display indicates that the installation is successful, Mac Novice use brew must pay more attention to the execution of some information after the command, it is suggested that MongoDB installation path is/usr/local/cellar/mongodb, If you need to modify the configuration information MongoDB can execute the command mongod--config/usr/local/etc/mongod.conf;

7. Configuration

After the installation is successful, do not rush to start, if it has been successfully used, then you can ignore the configuration of this item, configure the first to know that the default directory storage database is the root directory of data/db;

Mkdir-p/data/db           //need to create a directory to write directories for mongodb default data
Chown ' id-u '/data/db      //Give the directory you just created with read and writable permissions
MONGO--dbpath dir_name     //can also modify the directory, Dir_name for your directory name

8. Start

After the configuration of the above information can be launched, in fact, using brew to manage these software is particularly convenient, all the commands are almost the same;

Brew Services Start Mongodb/mongod

If the "successfully started ' MongoDB" appears as shown, this means that the start is successful;

9. Connect

After successful startup, execute the MONGO command to connect to the database, which may appear:

If the displayed content appears successfully and an arrow appears indicating that the database connection was successful, If the connection is not successful may be due to your previous use is not normal shutdown caused by the production of the Mongod.lock file, meaning that the database is temporarily locked, you can find the file is deleted and restarted, if still not able to use the command Ps-aef | grep MONGO view the process of possession, through the command kill-9 ID (process number) kill this no longer use the process, try to restart it;

10. Create a database (increase)

MongoDB has the following syntax format for creating a new database: (the default database is test, if you do not create a new database, the collection will be stored in the test database)

Show databases    //  show to  see which databases are available, or show Dbsuse demo/Use to           create a  database (if the database does not exist, create a number or switch to the specified database) show collections   //  view which collections (collections equivalent to one table in SQL) db.createcollection (' movie ')        //  Create a collection (equivalent to creating a table)

11. Deleting a database (delete)

The syntax format for MongoDB database deletion is as follows: (delete the current database, default is test, you can use the DB command to view the current database name, this command must learn, delete the library to run the necessary)

Db.dropdatabase ()        //  Delete the current database, you can select the database with use to delete Db.collection.drop ()     //  Delete the collection in the current database collection

12. Insert database (plug in)

MongoDB uses the Insert () or Save () method to insert data into the collection, with the following syntax:

Db.collection.insert (document)  //  to insert data into the collection collection, if the collection is not in the database, MongoDB The set is automatically created by merging the Insert document (documents)    //  If the _id field is not specified, the Save () method is similar to the Insert () method. If the _id field is specified, the data for the _id is updated

  insert插数据时There are a few points to note:

    • 1. Different key-value need to be separated by commas, while the middle of Key:value is written in standard JSON format by colon.
    • 2. If a key has more than one value,value to use []. Even if there is only one value at present, try to add [] for subsequent additions;
    • 3. The entire "data block" should be enclosed in {};
    • 4. If you do not specify an ID, the database will automatically create an ID number by default, in the same database, the ID number of each document is different;

13. Update the database (change)

MongoDB uses the update () and Save () methods to update the documents in the collection with the following syntax:

The update () method is used to update a document that already exists. The syntax format is as follows: Db.collection.update (   <query>,  //  update query criteria, similar to where in SQL update query   <update  and//Update  objects and some updated operators (such as $, $inc ...) ), and so on, can also be understood as   {     upsert: <boolean>,//optional, in SQL Update query after set,  This parameter means that if there is no record of update, Whether to insert objnew,true as INSERT, default is False, do not insert     Multi: <boolean>,  //optional  , MongoDB default is False, update only the first record found, If this parameter is true, it will be checked out on a per-condition basis. All Updates     writeconcern: <document>  //optional  , level of exception thrown   }) Save () method to replace an existing document with an incoming document. The syntax format is as follows: (   <document>,  //  document data, if all value values are changed with the previous document, it is re-created, So you must keep some value values equal to be updated;   {     writeconcern: <document>  //optional  , level of exception thrown;   })

14. Querying the database (check)

The MongoDB query document uses the Find () method. The Find () method displays all the documents in an unstructured way, and can pass in various query criteria, with the syntax of the query data as follows:

Db.collection.find (query, projection) query: Optional, use the query operator to specify the query condition; projection: optional, use the projection operator to specify the returned key. Returns all the key values in the document when queried, simply omit the parameter (omitted by default) Db.collection.find (). Pretty ()  //  Pretty () method to display all documents in a formatted manner Db.collection.findOne ()  //  return only one piece of data

15. Advanced ($type operator/limit ()/skip ()/sort ()/index/shard/backup/monitoring/extension)

Some common operational syntax formats for MongoDB more advanced are as follows:

Db.collection.find (). Pretty ()       //  formatted output Db.collection.find (). Count ()        //  View the number of documents in the collection Db.collection.find (). Skip ()         //  Skip the specified number of data Db.collection.find (). Limit ()        //  Reads the number of bars of the specified record Db.collection.find (). Sort ({key:1})  //  Specify the sorted field by parameter, and use 1 and-one to specify how to sort, where 1 is in ascending order, And-1 is used in descending order db.collection.getIndexes ()          //  View collection index condition db.collection.dropIndexes ()         //  Delete index (does not delete _ ID index) db.collection.createIndex ({key:1})  //  CREATE INDEX (parameter key is the index field you want to create, 1 to create an index in ascending order- 1 to create an index in descending order) Db.collection.aggregate ($group)     //  aggregation is primarily used to process data (such as averages, sums, etc.) and returns the computed data results, similar to COUNT (*) in SQL statements. $GT greater than $gte greater than or equal to $lt less than $lte less than equals $ne not equal to

These advanced common operations, the specific use of the official document can be viewed, of course, you are interested in the Chinese community can contribute;

16. Summary

MongoDB Learning also has a few days, and now finally have time to summarize the record down, this article is mainly some of the core of MongoDB, more suitable for Mac Novice learning, specific operating code also posted out, you can walk a lot of detours, if you also step by step with the steps learned here, Should be considered the basic introduction, as to give up is also a kind of beauty, since insisted on learning here, I believe you will not give up. In fact, this is only a year ago a major project of the foundation work, the next ready to start the development of Vue+webpack+es6+nodejs+mongodb full stack project, if you want to learn, welcome to continue to follow me!

my blog : Http://

my web: Https://

my public number : Tiandaochouqin Lewis

Novice Mac from Getting started to giving up MongoDB

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.