


Learning about addition, deletion, modification and query in node in mongoDB
The content of this article is about learning about adding, deleting, modifying and checking in nodes in mongoDB. It has a good reference value and I hope it can help friends in need.
Preparation
First, to use mongoDB in node, you need to install the MongoDB Driver. The command is as follows: npm install mongodb --save
github address: node- mongodb-native
At the same time, remember to enable the mongoDB service.
increase
The following code will insert a document into the tasks collection in the database demodb, and print the document's ID on the console.
const MongoClient = require('mongodb').MongoClient const assert = require('assert') const url = 'mongodb://localhost:27017' const dbName = 'demodb' // 增 MongoClient.connect(url, function(err, client) { assert.equal(null, err) console.log("Connected successfully to server") const db = client.db(dbName) var tasks = db.collection('tasks') // 没有则创建 tasks.insertOne( { "project": "task1", "description": "task1 description." }, {safe: true}, function(err, documents) { if (err) throw err; console.log(documents.insertedId); } ); client.close() })
Run the program and found that the following results were printed on the console
Connected successfully to server 5b59d53ae3d895184824586b
The returned 5b59d53ae3d895184824586b
is the document identifier of MongoDB. It is unique and its The essence is binary JSON (ie BSON). BSON is the main data format used by MongoDB to exchange data. The MongoDB server uses it to exchange data instead of JSON. In most cases it is more space efficient and faster to parse.
The declared {safe: true} indicates that the callback function will not be executed until the database operation is completed.
Note: For convenience, the authorization mode is not enabled here. Therefore, you can add, delete, modify and check at will without the username and password in the login URL. But in the production environment, please remember to turn on the authorization mode.
Delete
The following code will find the document whose project is task1 in the tasks collection in the database demodb and delete it.
// 删 MongoClient.connect(url, function(err, client) { assert.equal(null, err) console.log("Connected successfully to server") const db = client.db(dbName) var tasks = db.collection('tasks') tasks.deleteOne( { "project": "task1" }, function(err, result) { assert.equal(err, null); assert.equal(1, result.result.n); console.log("Removed the document"); } ); client.close() })
Note: If there are multiple documents with project task1 in the tasks collection, then only the first day's document found will be deleted.
Change
The following code will find the document whose project is task1 in the tasks collection in the database demodb and update it.
// 改 MongoClient.connect(url, function(err, client) { assert.equal(null, err) console.log("Connected successfully to server") const db = client.db(dbName) var tasks = db.collection('tasks') tasks.updateOne( { "project": "task1" }, { $set: { "project" : "task999" } }, {safe: true}, function(err, result) { assert.equal(err, null); assert.equal(1, result.result.n); console.log("Updated the document"); } ); client.close() })
Note: If the document with project task1 is not found in the tasks collection, the program will throw an assertion error, as follows:
Check
The following code will find all documents in the tasks collection in the database demodb and print them to the console.
// 查 MongoClient.connect(url, function(err, client) { assert.equal(null, err) console.log("Connected successfully to server") const db = client.db(dbName) var tasks = db.collection('tasks') tasks.find().toArray((err, docs) => { console.log(docs) assert.equal(null, err) // err 不等于null, 则在控制台打印err // assert.equal(3, docs.length) // 记录不等于3条, 则在控制台打印记录条数 }) client.close() })
The find() method finds all documents, toArray() converts the results into array form, and runs the program. The results are as follows:
Summary
Although the above four small programs are slightly simple, you can't reach a thousand miles without taking small steps. If you really master the basic addition, deletion, modification and search, then it is only a matter of time before you master complex applications. .
Related recommendations:
Introduction to users and permissions in mongoDB
The above is the detailed content of Learning about addition, deletion, modification and query in node in mongoDB. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools
