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

边栏推荐
- [beauty of algebra] solution method of linear equations ax=0
- 【组队 PK 赛】本周任务已开启 | 答题挑战,夯实商品详情知识
- MYSQL 对字符串类型排序不生效问题
- Android 隐私沙盒开发者预览版 3: 隐私安全和个性化体验全都要
- 编辑器-vi、vim的使用
- [reading notes] Figure comparative learning gnn+cl
- VS Code问题:长行的长度可通过 “editor.maxTokenizationLineLength“ 进行配置
- [ManageEngine] how to make good use of the report function of OpManager
- Applet (use of NPM package)
- Rebuild my 3D world [open source] [serialization-3] [comparison between colmap and openmvg]
猜你喜欢

Summary and Reflection on issues related to seq2seq, attention and transformer in hands-on deep learning

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

混淆矩阵(Confusion Matrix)

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

图神经网络+对比学习,下一步去哪?

【组队 PK 赛】本周任务已开启 | 答题挑战,夯实商品详情知识

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

Wxml template syntax
![[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)

Nodejs modularization
随机推荐
Attention is all you need
OpenGL - Model Loading
Kotlin introductory notes (I) kotlin variables and non variables
深入浅出PyTorch中的nn.CrossEntropyLoss
Unity SKFramework框架(二十四)、Avatar Controller 第三人称控制
利用请求头开发多端应用
Applet (global data sharing)
C # image difference comparison: image subtraction (pointer method, high speed)
一次 Keepalived 高可用的事故,让我重学了一遍它
Introduction Guide to stereo vision (2): key matrix (essential matrix, basic matrix, homography matrix)
Hi Fun Summer, play SQL planner with starrocks!
scipy. misc. imread()
Ministry of transport and Ministry of Education: widely carry out water traffic safety publicity and drowning prevention safety reminders
nodejs_ 01_ fs. readFile
我的一生.
[code practice] [stereo matching series] Classic ad census: (5) scan line optimization
Summary and Reflection on issues related to seq2seq, attention and transformer in hands-on deep learning
【PyTorch Bug】RuntimeError: Boolean value of Tensor with more than one value is ambiguous
MYSQL 对字符串类型排序不生效问题
Understanding rotation matrix R from the perspective of base transformation