node.js operation mongoDB database example sharing_node.js
Connect to database
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
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:
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
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
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
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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

MongoDB and relational database: In-depth comparison This article will explore in-depth the differences between NoSQL database MongoDB and traditional relational databases (such as MySQL and SQLServer). Relational databases use table structures of rows and columns to organize data, while MongoDB uses flexible document-oriented models to better suit the needs of modern applications. Mainly differentiates data structures: Relational databases use predefined schema tables to store data, and relationships between tables are established through primary keys and foreign keys; MongoDB uses JSON-like BSON documents to store them in a collection, and each document structure can be independently changed to achieve pattern-free design. Architectural design: Relational databases need to pre-defined fixed schema; MongoDB supports

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512
