Home Web Front-end JS Tutorial node.js operation mongoDB database example sharing_node.js

node.js operation mongoDB database example sharing_node.js

May 16, 2016 pm 04:30 PM
mongodb node.js operate database

Connect to database

Copy code The code is as follows:

var mongo=require("mongodb");
var host="localhost";
var port=mongo.Connection.DEFAULT_PORT;
var server=new mongo.Server(host,port,{auto_reconnect:true});//Create the server server where the database is located
var db=new mongo.Db("node-mongo-examples",server,{safe:true});//Create database object
db.open(function (err,db) {//Connect to database
If(err)
           throw err;
       else{
console.log("Database connection successfully established");
          db.close();
}
});
db.on("close", function (err,db) {//Close the database
If(err) throw err;
         else console.log("Database closed successfully.");
});

Insert data:

After inserting data, output the contents of the data document in the console

Copy code The code is as follows:

var mongo=require("mongodb");
var host="localhost";
var port=mongo.Connection.DEFAULT_PORT;
var server=new mongo.Server(host,port,{auto_reconnect:true});//Create the server server where the database is located
var db=new mongo.Db("node-mongo-examples",server,{safe:true});//Create database object
db.open(function (err,db) {//Connect to database
If(err)
           throw err;
       else{
           db.collection("users", function (err,collection) {
               collection.insert({username:"Panpan", firstname:"李"}, function (err,docs) {
console.log(docs);
              db.close();
             });
         });                                                    }
});
db.on("close", function (err,db) {//Close the database
If(err) throw err;
         else console.log("Database closed successfully.");
});

Close the databasedb.close([forceClose],[callback]);

When forceClose is true, the database is forcibly closed. After the database is closed, open cannot be used to open the database.

When forceClose is false, the database is not forced to close. When the database is closed, it can be opened again using open.

When foreClose is true:

Copy code The code is as follows:

var mongo=require("mongodb");
var host="localhost";
var port=mongo.Connection.DEFAULT_PORT;
var server=new mongo.Server(host,port,{auto_reconnect:true});//Create the server server where the database is located
var db=new mongo.Db("node-mongo-examples",server,{safe:true});//Create database object
db.open(function (err,db) {//Connect to database
If(err)
           throw err;
       else{
           db.collection("users", function (err,collection) {
               collection.insert({username:"Panpan", firstname:"李"}, function (err,docs) {
console.log(docs);
                db.close(false);
             });
          });
}
});
db.once("close", function (err,db) {//Close the database
If(err) throw err;
       else {
        db.open(function (err,db) {
            db.collection("users", function (err,collection) {
                   collection.insert({username:"三", firstname:"张"}, function (err,docs) {
If(err) throw err;
                     else{
console.log(docs);
                                                                        db.close(true);
                    }
                  })
             });
          });
}
});

//Read data

Copy code The code is as follows:

var mongo=require("mongodb");
var host="localhost";
var port=mongo.Connection.DEFAULT_PORT;
var server=mongo.Server(host,port,{auto_reconnect:true});
var db=new mongo.Db("node-mongo-examples",server,{safe:true});
db.open(function (err,db) {
db.collection("users", function (err,collection) {
If(err) throw err;
        else{
               collection.find({}).toArray(function(err,docs){
If(err) throw err;
                 else{
console.log(docs);
                    db.close();
                }
            });
}
});
});

//Search with query conditions

Copy code The code is as follows:

var mongo=require("mongodb");
var host="localhost";
var port=mongo.Connection.DEFAULT_PORT;
var server=mongo.Server(host,port,{auto_reconnect:true});
var db=new mongo.Db("node-mongo-examples",server,{safe:true});
db.open(function (err,db) {
db.collection("users", function (err,collection) {
If(err) throw err;
        else{
              collection.find({username:{$in:["Yansi","三"]}}).toArray(function(err,docs){
If(err) throw err;
                 else{
console.log(docs);
                    db.close();
                }
            });
}
});
});

//Insert a batch of data, and search for type==food and the price field value is less than 10

Copy code The code is as follows:

var mongo=require("mongodb");
var host="localhost";
var port=mongo.Connection.DEFAULT_PORT;
var server=mongo.Server(host,port,{auto_reconnect:true});
var db=new mongo.Db("node-mongo-examples",server,{safe:true});
var docs=[
{type:"food",price:11},
{type:"food",price:10},
{type:"food",price:9},
{type:"food",price:8},
{type:"book",price:9}
];
db.open(function (err,db) {
db.collection("goods", function (err,collection) {
If(err) throw err;
        else{
               collection.insert(docs, function (err,docs) {
If(err) throw err;
                 else{
                              collection.find({type:"food",price:{$lt:10}}).toArray(
function(err,docs){
If(err) throw err;
                                                                                                                                                                                                                                                                                                 Since console.log(docs);
                                                                                                                                                                                                                                                                                   }                                                                                                           } );
                }
             })
}
});
});




The expression of or in query
:

Copy code

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

PHP Database Connection Pitfalls: Avoid Common Mistakes and Misunderstandings PHP Database Connection Pitfalls: Avoid Common Mistakes and Misunderstandings Jun 05, 2024 pm 10:21 PM

To avoid PHP database connection errors, follow best practices: check for connection errors and match variable names with credentials. Use secure storage or environment variables to avoid hardcoding credentials. Close the connection after use to prevent SQL injection and use prepared statements or bound parameters.

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

How to ensure high availability of MongoDB on Debian How to ensure high availability of MongoDB on Debian Apr 02, 2025 am 07:21 AM

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

Major update of Pi Coin: Pi Bank is coming! Major update of Pi Coin: Pi Bank is coming! Mar 03, 2025 pm 06:18 PM

PiNetwork is about to launch PiBank, a revolutionary mobile banking platform! PiNetwork today released a major update on Elmahrosa (Face) PIMISRBank, referred to as PiBank, which perfectly integrates traditional banking services with PiNetwork cryptocurrency functions to realize the atomic exchange of fiat currencies and cryptocurrencies (supports the swap between fiat currencies such as the US dollar, euro, and Indonesian rupiah with cryptocurrencies such as PiCoin, USDT, and USDC). What is the charm of PiBank? Let's find out! PiBank's main functions: One-stop management of bank accounts and cryptocurrency assets. Support real-time transactions and adopt biospecies

See all articles