当前位置:网站首页>Node の MongoDB Driver
Node の MongoDB Driver
2022-07-05 09:26:00 【InfoQ】
序
MongoDBCompassMongoDB- mongodb: MongoDB有一个基础库
mongodb(Node.js MongoDB Driver)
- Mongoose: 现在主流使用的库,在代码量上更优,只需增删改查推荐
mongodb
下载
yarn add mongodbmongodb
连接
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("数据库已创建!");
db.close();
});
}

mongodbTestcompass




MongoClient.dbconst baseUrl = 'mongodb://127.0.0.1:27017'
// 创建对象
const client = new MongoClient(baseUrl);
async function TestConnect() {
try {
// 连接到数据库
await client.connect();
// 使用之前手动创建的mongodbTest数据库
const db = await client.db('mongodbTest');
console.log(db.databaseName)
// 创建一个新的集合 (如果是代码新建的数据库,那么必须创建一个集合)
db.createCollection('collection01')
} catch(e) {
console.log(e)
await client.close();
}
}
module.exports = { TestConnect }
获取集合列表
collectionscollectionName// 连接到数据库
await client.connect();
// 使用之前手动创建的mongodbTest数据库
const db = await client.db('mongodbTest');
// 获取当前数据库下所有集合
let collections = await db.collections();
// 打印集合名称
collections.forEach(item=>{
console.log(item.collectionName)
})


创建集合并插入数据

// 创建新集合
db.createCollection('collection03', { autoIndexId: true }, (err, res)=>{
if (err) console.log('集合创建失败');
console.log(res.collectionName) // collection03
})insertOne// 使用集合collection03
let c3 = db.collection('collection03');
// 定义文档
let doc = {
name: '张三',
age: 18,
hobby: '打李四',
}
// 将文档插入集合
const result = await c3.insertOne(doc);


- insert: 将单个文档或文档数组插入MongoDB。如果传入的文档不包含\u id字段,驱动程序将向缺少该字段的每个文档中添加一个,从而改变文档
- insertMany: 将文档数组插入MongoDB。如果传入的文档不包含\u id字段,驱动程序将向缺少该字段的每个文档中添加一个,从而改变文档
- insertOne: 将单个文档插入MongoDB。如果传入的文档不包含\u id字段,驱动程序将向缺少该字段的每个文档中添加一个,从而改变文档
let doc = [
{
name: '李四',
age: 18,
hobby: '打王五',
},
{
name: '王五',
age: 18,
hobby: '打张三',
},
]
// 将文档插入集合
const result = await c3.insertMany(doc);


读取集合中的数据
MongoDBfind
// 读取集合中数据
const res = await c3.find().toArray();
console.log(res)
findprojectionMongoServerError: Cannot do inclusion on field name in exclusion projection_idage// 读取集合中数据
const res = await c3.find({}, {
projection: { _id: 0, age: 0 }
}).toArray();
console.log(res)
find{}// 读取集合中数据
const res = await c3.find({
name: /张/
}, {
projection: { _id: 0, age: 0 }
}).toArray();
console.log(res)
删除集合信息

// 读取集合中数据
const res = await c3.deleteOne({
name: /张/
});
console.log(res) // { acknowledged: true, deletedCount: 1 }
更新集合

// 读取集合中数据
let newvalue = { $set: { hobby: '打李四' } }
const res = await c3.updateOne({
name: /王/
}, newvalue);
console.log(res)

边栏推荐
- Introduction Guide to stereo vision (4): DLT direct linear transformation of camera calibration [recommended collection]
- Unity SKFramework框架(二十二)、Runtime Console 运行时调试工具
- Ministry of transport and Ministry of Education: widely carry out water traffic safety publicity and drowning prevention safety reminders
- Svg optimization by svgo
- Introduction Guide to stereo vision (7): stereo matching
- 生成对抗网络
- 深入浅出PyTorch中的nn.CrossEntropyLoss
- NIPS2021 | 超越GraphCL,GNN+对比学习的节点分类新SOTA
- Confusion matrix
- Greendao reported an error in qigsaw, could not init daoconfig
猜你喜欢

OpenGL - Lighting

Android privacy sandbox developer preview 3: privacy, security and personalized experience

Nips2021 | new SOTA for node classification beyond graphcl, gnn+ comparative learning

Generate confrontation network

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

22-07-04 Xi'an Shanghao housing project experience summary (01)

LeetCode 503. 下一个更大元素 II

Can't find the activitymainbinding class? The pit I stepped on when I just learned databinding

Android 隐私沙盒开发者预览版 3: 隐私安全和个性化体验全都要

Creation and reference of applet
随机推荐
[ctfhub] Title cookie:hello guest only admin can get flag. (cookie spoofing, authentication, forgery)
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
图神经网络+对比学习,下一步去哪?
VS Code问题:长行的长度可通过 “editor.maxTokenizationLineLength“ 进行配置
2310. 个位数字为 K 的整数之和
[code practice] [stereo matching series] Classic ad census: (4) cross domain cost aggregation
Applet data attribute method
Kotlin introductory notes (I) kotlin variables and non variables
Progressive JPEG pictures and related
2309. The best English letters with both upper and lower case
Applet (global data sharing)
.NET服务治理之限流中间件-FireflySoft.RateLimit
It's too difficult to use. Long articles plus pictures and texts will only be written in short articles in the future
Ministry of transport and Ministry of Education: widely carry out water traffic safety publicity and drowning prevention safety reminders
一题多解,ASP.NET Core应用启动初始化的N种方案[上篇]
Android 隐私沙盒开发者预览版 3: 隐私安全和个性化体验全都要
Kotlin introductory notes (VII) data class and singleton class
notepad++
22-07-04 西安 尚好房-项目经验总结(01)