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

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


Directory
    • 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


MongoDB



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: http://coolshell.cn/articles/5826.html



Website address: http://www.mongodb.org/



API docs:http://docs.mongodb.org/manual/



Node-mongodb-native



MongoDB's Nodejs Drive;



GitHub Address: Https://github.com/mongodb/node-mongodb-native


MongoDB installation (Windows)


Official Installation Instructions: http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/



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://www.mongodb.org/downloads



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



##database directory
Dbpath=C:\M_DB

##Log output file
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



" 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



Mongo





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: http://docs.mongodb.org/manual/reference/program/


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 ^_^!






  Insert



  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






  Inquire  



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 ^_^!






  Modify



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"}});









  Delete



db. Table name. Remove (condition);









  Stored Procedures



To create a stored procedure:



Db.system.js.save({_id:"Stored Procedure ID",
Value:function(parameter){
         -- the logical body;
         Return
}});


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



Install MongoDB


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






Insert



Var MongoClient = require(‘mongodb‘).MongoClient;
Var DB_CONN_STR = ‘mongodb://localhost:27017/wilsondb1‘;

Var insertData = function(db, callback) {
     //Connect to the table
     Var collection = db.collection(‘tb2‘);
     / / Insert data
     Var data = [{"name":‘wilson001‘,"age":21},{"name":‘wilson002‘,"age":22}];
     Collection.insert(data, function(err, result) {
         If(err)
         {
             Console.log(‘Error:‘+ err);
             Return;
         }
         Callback(result);
     });
}

MongoClient.connect(DB_CONN_STR, function(err, db) {
     Console.log("Connection succeeded!");
     insertData(db, function(result) {
         Console.log(result);
         Db.close();
     });
}); 
Sample Source Code


  Inquire



Var MongoClient = require(‘mongodb‘).MongoClient;
Var DB_CONN_STR = ‘mongodb://localhost:27017/wilsondb1‘;

Var selectData = function(db, callback) {
   //Connect to the table
   Var collection = db.collection(‘tb2‘);
   //Query data
   Var whereStr = {"name":‘wilson001‘};
   Collection.find(whereStr).toArray(function(err, result) {
     If(err)
     {
       Console.log(‘Error:‘+ err);
       Return;
     }
     Callback(result);
   });
}

MongoClient.connect(DB_CONN_STR, function(err, db) {
   Console.log("Connection succeeded!");
   selectData(db, function(result) {
     Console.log(result);
     Db.close();
   });
}); 
Sample Source Code


  Modify



Var MongoClient = require(‘mongodb‘).MongoClient;
Var DB_CONN_STR = ‘mongodb://localhost:27017/wilsondb1‘;

Var updateData = function(db, callback) {
     //Connect to the table
     Var collection = db.collection(‘tb2‘);
     //update data
     Var whereStr = {"name":‘wilson001‘};
     Var updateStr = {$set: { "age" : 100 }};
     Collection.update(whereStr,updateStr, function(err, result) {
         If(err)
         {
             Console.log(‘Error:‘+ err);
             Return;
         }
         Callback(result);
     });
}

MongoClient.connect(DB_CONN_STR, function(err, db) {
     Console.log("Connection succeeded!");
     updateData(db, function(result) {
         Console.log(result);
         Db.close();
     });
}); 
Sample Source Code


  Delete



Var MongoClient = require(‘mongodb‘).MongoClient;
Var DB_CONN_STR = ‘mongodb://localhost:27017/wilsondb1‘;

Var delData = function(db, callback) {
   //Connect to the table
   Var collection = db.collection(‘tb2‘);
   //delete data
   Var whereStr = {"name":‘wilson001‘};
   Collection.remove(whereStr, function(err, result) {
     If(err)
     {
       Console.log(‘Error:‘+ err);
       Return;
     }
     Callback(result);
   });
}

MongoClient.connect(DB_CONN_STR, function(err, db) {
   Console.log("Connection succeeded!");
   delData(db, function(result) {
     Console.log(result);
     Db.close();
   });
}); 
Sample Source Code


  Call a stored procedure



Var MongoClient = require(‘mongodb‘).MongoClient;
Var DB_CONN_STR = ‘mongodb://localhost:27017/wilsondb1‘;

Var invokeProcData = function(db, callback) {
     / / stored procedure call
     Db.eval(‘get_tb2_count()', function(err, result) {
         If(err)
         {
             Console.log(‘Error:‘+ err);
             Return;
         }
         Callback(result);
     });
}

MongoClient.connect(DB_CONN_STR, function(err, db) {
     Console.log("Connection succeeded!");
     invokeProcData(db, function(result) {
         Console.log(result);
         Db.close();
     });
}); 
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;






Main references:



http://docs.mongodb.org/manual/



Https://github.com/mongodb/node-mongodb-native



MongoDB Authoritative Guide



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