当前位置:网站首页>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)

边栏推荐
- Principle and performance analysis of lepton lossless compression
- C language - input array two-dimensional array a from the keyboard, and put 3 in a × 5. The elements in the third column of the matrix are moved to the left to the 0 column, and the element rows in ea
- Multiple solutions to one problem, asp Net core application startup initialization n schemes [Part 1]
- Introduction Guide to stereo vision (6): level constraints and polar correction of fusiello method
- Applet global style configuration window
- Rebuild my 3D world [open source] [serialization-1]
- Kotlin introductory notes (III) kotlin program logic control (if, when)
- Huber Loss
- Priority queue (heap)
- [beauty of algebra] solution method of linear equations ax=0
猜你喜欢
![一题多解,ASP.NET Core应用启动初始化的N种方案[上篇]](/img/c4/27ae0d259abc4e61286c1f4d90c06a.png)
一题多解,ASP.NET Core应用启动初始化的N种方案[上篇]

LeetCode 556. Next bigger element III

C language - input array two-dimensional array a from the keyboard, and put 3 in a × 5. The elements in the third column of the matrix are moved to the left to the 0 column, and the element rows in ea
![[team PK competition] the task of this week has been opened | question answering challenge to consolidate the knowledge of commodity details](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[team PK competition] the task of this week has been opened | question answering challenge to consolidate the knowledge of commodity details

项目实战 | Excel导出功能

LeetCode 556. 下一个更大元素 III

Lepton 无损压缩原理及性能分析

Applet (use of NPM package)

L'information et l'entropie, tout ce que vous voulez savoir est ici.

【ManageEngine】如何利用好OpManager的报表功能
随机推荐
【饿了么动态表格】
Principle and performance analysis of lepton lossless compression
Using request headers to develop multi terminal applications
阿里十年测试带你走进APP测试的世界
【对象数组a与对象数组b取出id不同元素赋值给新的数组】
Jenkins pipeline method (function) definition and call
云计算技术热点
SQL learning group by multi table grouping scenario
顶会论文看图对比学习(GNN+CL)研究趋势
【阅读笔记】图对比学习 GNN+CL
【el-table如何禁用】
A detailed explanation of the general process and the latest research trends of map comparative learning (gnn+cl)
Figure neural network + comparative learning, where to go next?
Multiple solutions to one problem, asp Net core application startup initialization n schemes [Part 1]
[team PK competition] the task of this week has been opened | question answering challenge to consolidate the knowledge of commodity details
2311. 小于等于 K 的最长二进制子序列
2309. The best English letters with both upper and lower case
项目实战 | Excel导出功能
测试老鸟浅谈unittest和pytest的区别
信息与熵,你想知道的都在这里了