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

边栏推荐
- Applet network data request
- Hi Fun Summer, play SQL planner with starrocks!
- Greendao reported an error in qigsaw, could not init daoconfig
- Principle and performance analysis of lepton lossless compression
- Applet global style configuration window
- Kotlin introductory notes (VIII) collection and traversal
- [team PK competition] the task of this week has been opened | question answering challenge to consolidate the knowledge of commodity details
- Shutter uses overlay to realize global pop-up
- nodejs_ fs. writeFile
- C # draw Bezier curve with control points for lattice images and vector graphics
猜你喜欢

VS Code问题:长行的长度可通过 “editor.maxTokenizationLineLength“ 进行配置
![[ctfhub] Title cookie:hello guest only admin can get flag. (cookie spoofing, authentication, forgery)](/img/78/d9d1a66fc239e7c62de1fce426d30d.jpg)
[ctfhub] Title cookie:hello guest only admin can get flag. (cookie spoofing, authentication, forgery)

Nodemon installation and use

一次 Keepalived 高可用的事故,让我重学了一遍它

Generate confrontation network

一文详解图对比学习(GNN+CL)的一般流程和最新研究趋势

高性能Spark_transformation性能

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

Unity skframework framework (XXII), runtime console runtime debugging tool

Unity SKFramework框架(二十四)、Avatar Controller 第三人称控制
随机推荐
Blogger article navigation (classified, real-time update, permanent top)
Android privacy sandbox developer preview 3: privacy, security and personalized experience
notepad++
Applet data attribute method
【PyTorch Bug】RuntimeError: Boolean value of Tensor with more than one value is ambiguous
Rebuild my 3D world [open source] [serialization-2]
Lepton 无损压缩原理及性能分析
顶会论文看图对比学习(GNN+CL)研究趋势
Introduction Guide to stereo vision (3): Zhang calibration method of camera calibration [ultra detailed and worthy of collection]
一题多解,ASP.NET Core应用启动初始化的N种方案[上篇]
nodejs_ fs. writeFile
一题多解,ASP.NET Core应用启动初始化的N种方案[上篇]
Creation and reference of applet
Unity skframework framework (24), avatar controller third person control
2310. 个位数字为 K 的整数之和
STM32 simple multi-level menu (array table lookup method)
Node collaboration and publishing
Introduction Guide to stereo vision (7): stereo matching
[Yugong series] go teaching course 003-ide installation and basic use in July 2022
2311. Longest binary subsequence less than or equal to K