Nodejs Learning Notes (10)---interaction with mongodb (mongodb/node-mongodb-native), Getting started with MongoDB

Source: Internet
Author: User
Tags bulk insert install mongodb mongodb support

    • Brief introduction
    • MongoDB installation (Windows)
    • Getting Started with MongoDB basic syntax and operations (Mongo.exe client operations)
      • Library operations
      • Insert
      • Inquire
      • Modify
      • Delete
      • Stored Procedures
    • Nodejs manipulating MongoDB
      • Insert
      • Inquire
      • Modify
      • Delete
      • Call a stored procedure
    • Write in the following ...
Brief introduction


Open source, high-performance NoSQL database, support for indexing, clustering, replication and failover, drivers for various languages, high scalability;

NoSQL is still at the stage of development, and there are various questions about it:

Website address:

API docs:


MongoDB's Nodejs Drive;

GitHub Address: Https://

MongoDB installation (Windows)

Official Installation Instructions:

According to the official instructions in the Win7 64-bit environment to configure or have encountered a problem, I still have to write my installation configuration process


  Download MongoDB and install

: Http://

Create a database and log storage directory

Create a new "m_db" and "M_log" two folders under the C packing directory, respectively, to hold the database files and log files.

Create a config file

Open the directory "C:\Program Files\mongodb 2.6 standard\bin" and create a new Mongo.config file in this directory with the following file contents

# #数据库目录dbpath =c:\m_db# #日志输出文件logpath =c:\m_log\mongodb.log

Adding environment variables

Add "C:\Program Files\mongodb 2.6 standard\bin" to the environment variable path

Running MongoDB with Windows Server

Open the CMD window as an administrator, run the following command to install the MongoDB service, you can find a service named "MongoDB" in "Control Panel \ All Control Panel items \ Administrative Tools \ Services" Right-click Start

Mongod--config "C:\Program files\mongodb 2.6 standard\bin\mongo.config"--install

Start the service

Run the following command in the cmd window, or you can do so in the control Panel \ All Control Panel items \ Administrative Tools \ Services

net start MongoDB

Test connection

Run the following command in CMD to view the results



Installation is successful!

The last two steps are not required; MongoDB default port is 27017, can be modified!

For the "C:\Program Files\mongodb 2.6 standard\bin" directory under the EXE program, do a simple explanation, may be more conducive to understanding what can be done, basic learning focus on mongod.exe and Mongo.exe can

Mongo.exe: Client, support JS syntax

Mongod.exe: Service Side

Mongodump.exe: Backup tool

Mongorestore.exe: Recovery Tool

Mongoexport.exe: Export Tool

Mongoimport.exe: Import Tool

Mongostat.exe: Real-time performance monitoring tool

Mongotop.exe: Tracking Mongdb Instance read-Write Time tool

More detailed explanations or actions can be viewed:

Getting Started with MongoDB basic syntax and operations (Mongo.exe client operations)

MongoDB has been installed, the following first a simple introduction to MongoDB, and then use Node-mongodb-native to operate MongoDB

  Library operations

New database: The first step: Use the new database name; second step: Do the library related operations; If you do not take the second step, the database will not be created

View database: Show DBS;

New table: Db.createcollection (' new table name to be created ');

View current database table below: Show collections;

Deletes the current database specified table: DB. Table name. Drop ();

Delete Current database: Db.dropdatabase ();

Example operations such as:


1. The default is the existence of "admin" and "local" two databases, the admin database is the database that holds the administrator information, the authentication will be used, and the local is to store replication related data;

2.find (); It is a query operation, and later, it is used primarily to demonstrate that the use of a library is not present, the relevant operation will create this library;

3.MongoDB not like MySQL or MSSQL database such strict rules, not have to build a library, build tables, build all kinds of fields, later operation will slowly experience the ^_^!



  method One:db. Table name. Insert (data);


1. From the operation can be seen, did not go to create "tb1" table, in fact, through the insert operation will also be automatically created

2._ID, is a mongodb self-generated, each row of data will exist, the default is Objectid, you can insert the data when the value of this key (supporting MONGODB support for all data types)

  method Two:db. Table name. Save (data);

1. From the operation can be seen, save can also achieve insert-like effect

2._ID can be self-inserted

3. A table does not necessarily have the same fields

What's the difference between them?


Operation can be seen, although the insert and save methods can be inserted data, when the default "_id" value already exists, call insert method inserts will error, and the Save method will not update the same _id row data information


Querying all data in a table: db. Table name. find ();

Query by criteria (multi-criteria supported): DB. Table name. find (condition);

Query first (support condition): DB. Table name. FindOne (conditions);

Limit quantity: DB. Table name. Find (). Limit (qty);

Skips the specified number: DB. Table name. Find (). Skip (qty);


You can see the specific usage, BULK INSERT default data I used a JavaScript syntax loop;


Compare queries

Greater than: $GT

Less than: $lt

Greater than or equal to: $gte

Less than or equal to: $lte

Not equal to: $ne


What do you think of the relationship between and?

Or: $or



In and not in queries (contains, does not contain) $in $nin

Number of queries: DB. Table name. Find (). Count ();

Sort: db. Table name. Find (). Sort ({"Field name": 1});

1: Indicates ascending-1: Indicates descending order

The specified field returns: DB. Table name. Find ({},{"field name": 0});

1: Return 0: Do not return



The query is about here, the feeling of query example is not finished, there are some advanced query, we go to understand it ^_^!



The previous save in the _id field already exists is the modify operation, the syntax is modified by the specified conditions as follows

db. Table name. Update ({"Condition field name": "Field value"},{$set: {"Field name to modify": "Modified field Value"}});



db. Table name. Remove (condition);


  Stored Procedures

To create a stored procedure: ({_id: "Stored procedure ID", value:function (parameter) {          --logical body;         return returns; }});                

Call a stored procedure

Db.eval ("Stored procedure ID ()");


All stored procedures are kept in db.system.js

MongoDB Basic operation is said so much, basic enough, in-depth study we have to see the API ^_^!

Nodejs manipulating MongoDB

Install MongoDB with NPM first

NPM Install MongoDB

After the installation succeeds, proceed to the libraries and tables created in the actions above



Sample Source Code


Sample Source Code


Sample Source Code


Sample Source Code

  Call a stored procedure

Sample Source Code

This crud operation is done, and the result parameter of the callback function can be used to determine the further combination of business logic!

Write in the following ...

This article for node-mongodb-native operation MongoDB did not do a deeper explanation, because it is to carry out a lot of packaging, and more conducive to the implementation of programming, such as: Mongoose, Mongoskin, Mongolian and so on, the application is good;

Mongoose may be used more ...

Many places in this article I am still accustomed to use the terms of table, line and so on to describe, in fact, is not right for NoSQL, but to help get used to the relational database developers to solve;

The article "table" should be described as "collection (collection)"; "line" should be described as "document", a database can have multiple collection, a collection can have more than one document

The article does not involve the certification of the part, we go to fill up, very simple, I also survived the two default database of the "admin" database

When using the Mongo.exe operation in cmd, inserting Chinese encounters a problem, because MongoDB default edit is Utf-8, and CMD is GBK, so execute this command in CMD window Modify edit: Chcp 65001

Note that MongoDB is strictly case-sensitive, such as querying Db.tb2.find ({"Name": "Wilson0"}) and Db.tb2.find ({"Name": "Wilson0"}) are not used in the same field as the condition;

Nodejs Learning Notes (10)---interaction with mongodb (mongodb/node-mongodb-native), Getting started with 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.