当前位置:网站首页>Node の MongoDB Driver
Node の MongoDB Driver
2022-07-05 09:29:00 【InfoQ】
order
MongoDBCompassMongoDB- mongodb: MongoDB There is a basic library
mongodb(Node.js MongoDB Driver)
- Mongoose: Now the mainstream Library , Better in the amount of code , Just add, delete, modify and check the recommendation
mongodb
download
yarn add mongodbmongodb
Connect
mongodbMongoClient
const MongoClient = require('mongodb').MongoClient;
const baseUrl = 'mongodb://127.0.0.1:27017/mongodbTest'
function TestConnect() {
MongoClient.connect(baseUrl, function(err, db) {
if (err) throw err;
console.log(" Database created !");
db.close();
});
}

mongodbTestcompass




MongoClient.dbconst baseUrl = 'mongodb://127.0.0.1:27017'
// Create objects
const client = new MongoClient(baseUrl);
async function TestConnect() {
try {
// Connect to database
await client.connect();
// Use the previously manually created mongodbTest database
const db = await client.db('mongodbTest');
console.log(db.databaseName)
// Create a new collection ( If the database is created by the code , Then you must create a set )
db.createCollection('collection01')
} catch(e) {
console.log(e)
await client.close();
}
}
module.exports = { TestConnect }
Get collection list
collectionscollectionName// Connect to database
await client.connect();
// Use the previously manually created mongodbTest database
const db = await client.db('mongodbTest');
// Get all collections under the current database
let collections = await db.collections();
// Print set name
collections.forEach(item=>{
console.log(item.collectionName)
})


Create a collection and insert data

// Create a new collection
db.createCollection('collection03', { autoIndexId: true }, (err, res)=>{
if (err) console.log(' Collection creation failed ');
console.log(res.collectionName) // collection03
})insertOne// Use set collection03
let c3 = db.collection('collection03');
// Define documents
let doc = {
name: ' Zhang San ',
age: 18,
hobby: ' Hit Li Si ',
}
// Insert the document into the collection
const result = await c3.insertOne(doc);


- insert: Insert a single document or an array of documents MongoDB. If the incoming document does not contain \u id Field , The driver will add a , Thus changing the document
- insertMany: Insert the document array MongoDB. If the incoming document does not contain \u id Field , The driver will add a , Thus changing the document
- insertOne: Insert a single document MongoDB. If the incoming document does not contain \u id Field , The driver will add a , Thus changing the document
let doc = [
{
name: ' Li Si ',
age: 18,
hobby: ' Beat Wang Wu ',
},
{
name: ' Wang Wu ',
age: 18,
hobby: ' Open three ',
},
]
// Insert the document into the collection
const result = await c3.insertMany(doc);


Read the data in the collection
MongoDBfind
// Read the data in the collection
const res = await c3.find().toArray();
console.log(res)
findprojectionMongoServerError: Cannot do inclusion on field name in exclusion projection_idage// Read the data in the collection
const res = await c3.find({}, {
projection: { _id: 0, age: 0 }
}).toArray();
console.log(res)
find{}// Read the data in the collection
const res = await c3.find({
name: / Zhang /
}, {
projection: { _id: 0, age: 0 }
}).toArray();
console.log(res)
Delete set information

// Read the data in the collection
const res = await c3.deleteOne({
name: / Zhang /
});
console.log(res) // { acknowledged: true, deletedCount: 1 }
Update collection

// Read the data in the collection
let newvalue = { $set: { hobby: ' Hit Li Si ' } }
const res = await c3.updateOne({
name: / king /
}, newvalue);
console.log(res)

边栏推荐
- 测试老鸟浅谈unittest和pytest的区别
- What is a firewall? Explanation of basic knowledge of firewall
- 浅谈Label Smoothing技术
- Unity SKFramework框架(二十三)、MiniMap 小地图工具
- A detailed explanation of the general process and the latest research trends of map comparative learning (gnn+cl)
- Kotlin introductory notes (III) kotlin program logic control (if, when)
- Deep understanding of C language pointer
- Rebuild my 3D world [open source] [serialization-2]
- 项目实战 | Excel导出功能
- Vs code problem: the length of long lines can be configured through "editor.maxtokenizationlinelength"
猜你喜欢

LeetCode 496. 下一个更大元素 I

Wxml template syntax

A detailed explanation of the general process and the latest research trends of map comparative learning (gnn+cl)

What is a firewall? Explanation of basic knowledge of firewall

Blogger article navigation (classified, real-time update, permanent top)

C form click event did not respond

LeetCode 556. 下一个更大元素 III
![[beauty of algebra] singular value decomposition (SVD) and its application to linear least squares solution ax=b](/img/ee/8e07e2dd89bed63ff44400fe1864a9.jpg)
[beauty of algebra] singular value decomposition (SVD) and its application to linear least squares solution ax=b

fs. Path module
![Introduction Guide to stereo vision (5): dual camera calibration [no more collection, I charge ~]](/img/68/6bfa390b0bedcdbc4afba2f9bd9c0f.jpg)
Introduction Guide to stereo vision (5): dual camera calibration [no more collection, I charge ~]
随机推荐
Composition of applet code
np. allclose
fs. Path module
Progressive JPEG pictures and related
Wechat applet obtains household area information
Analysis of eventbus source code
阿里云发送短信验证码
Information and entropy, all you want to know is here
MYSQL 对字符串类型排序不生效问题
【el-table如何禁用】
LeetCode 556. Next bigger element III
[Yugong series] go teaching course 003-ide installation and basic use in July 2022
Talking about the difference between unittest and pytest
Introduction Guide to stereo vision (5): dual camera calibration [no more collection, I charge ~]
Ministry of transport and Ministry of Education: widely carry out water traffic safety publicity and drowning prevention safety reminders
干货整理!ERP在制造业的发展趋势如何,看这一篇就够了
LeetCode 556. 下一个更大元素 III
基于STM32单片机的测温仪(带人脸检测)
【数组的中的某个属性的监听】
scipy. misc. imread()