当前位置:网站首页>Node の MongoDB Driver
Node の MongoDB Driver
2022-07-05 09:26:00 【InfoQ】
序
MongoDB
Compass
MongoDB
- mongodb: MongoDB有一个基础库
mongodb
(Node.js MongoDB Driver)
- Mongoose: 现在主流使用的库,在代码量上更优,只需增删改查推荐
mongodb
下载
yarn add mongodb
mongodb

连接
mongodb
MongoClient

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();
});
}

mongodbTest
compass





MongoClient.db
const 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 }
获取集合列表
collections
collectionName
// 连接到数据库
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);


读取集合中的数据
MongoDB
find

// 读取集合中数据
const res = await c3.find().toArray();
console.log(res)

find
projection
MongoServerError: Cannot do inclusion on field name in exclusion projection
_id
age
// 读取集合中数据
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)

边栏推荐
- 一篇文章带你走进cookie,session,Token的世界
- [code practice] [stereo matching series] Classic ad census: (5) scan line optimization
- Rebuild my 3D world [open source] [serialization-2]
- Driver's license physical examination hospital (114-2 hang up the corresponding hospital driver physical examination)
- nodejs_ fs. writeFile
- Applet global style configuration window
- [beauty of algebra] singular value decomposition (SVD) and its application to linear least squares solution ax=b
- Thermometer based on STM32 single chip microcomputer (with face detection)
- Attention is all you need
- Applet (global data sharing)
猜你喜欢
[beauty of algebra] singular value decomposition (SVD) and its application to linear least squares solution ax=b
Nodejs modularization
生成对抗网络
信息与熵,你想知道的都在这里了
3D reconstruction open source code summary [keep updated]
【ManageEngine】如何利用好OpManager的报表功能
高性能Spark_transformation性能
Unity SKFramework框架(二十四)、Avatar Controller 第三人称控制
[ctfhub] Title cookie:hello guest only admin can get flag. (cookie spoofing, authentication, forgery)
[ManageEngine] how to make good use of the report function of OpManager
随机推荐
【PyTorch Bug】RuntimeError: Boolean value of Tensor with more than one value is ambiguous
微信小程序获取住户地区信息
Newton iterative method (solving nonlinear equations)
Confusion matrix
Unity skframework framework (XXII), runtime console runtime debugging tool
Information and entropy, all you want to know is here
22-07-04 Xi'an Shanghao housing project experience summary (01)
[ctfhub] Title cookie:hello guest only admin can get flag. (cookie spoofing, authentication, forgery)
Wxss template syntax
图神经网络+对比学习,下一步去哪?
Creation and reference of applet
Alibaba cloud sends SMS verification code
2311. 小于等于 K 的最长二进制子序列
Kotlin introductory notes (III) kotlin program logic control (if, when)
2309. The best English letters with both upper and lower case
Jenkins Pipeline 方法(函数)定义及调用
22-07-04 西安 尚好房-项目经验总结(01)
C # image difference comparison: image subtraction (pointer method, high speed)
Thermometer based on STM32 single chip microcomputer (with face detection)
太不好用了,长文章加图文,今后只写小短文