当前位置:网站首页>Node の MongoDB Driver
Node の MongoDB Driver
2022-07-05 09:29:00 【InfoQ】
order
MongoDB
Compass
MongoDB
- 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 mongodb
mongodb

Connect
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(" Database created !");
db.close();
});
}

mongodbTest
compass





MongoClient.db
const 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
collections
collectionName
// 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
MongoDB
find

// Read the data in the collection
const res = await c3.find().toArray();
console.log(res)

find
projection
MongoServerError: Cannot do inclusion on field name in exclusion projection
_id
age
// 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)

边栏推荐
- Introduction Guide to stereo vision (5): dual camera calibration [no more collection, I charge ~]
- 测试老鸟浅谈unittest和pytest的区别
- Nodemon installation and use
- 信息与熵,你想知道的都在这里了
- 【愚公系列】2022年7月 Go教学课程 003-IDE的安装和基本使用
- Applet network data request
- Unity SKFramework框架(二十三)、MiniMap 小地图工具
- np. allclose
- Kotlin introductory notes (I) kotlin variables and non variables
- Kotlin introductory notes (IV) circular statements (simple explanation of while, for)
猜你喜欢
LeetCode 503. Next bigger Element II
Editor use of VI and VIM
What is a firewall? Explanation of basic knowledge of firewall
Rebuild my 3D world [open source] [serialization-3] [comparison between colmap and openmvg]
[ManageEngine] how to make good use of the report function of OpManager
Wxss template syntax
Information and entropy, all you want to know is here
Unity SKFramework框架(二十二)、Runtime Console 运行时调试工具
【阅读笔记】图对比学习 GNN+CL
LeetCode 496. 下一个更大元素 I
随机推荐
Huber Loss
SQL learning - case when then else
深入浅出PyTorch中的nn.CrossEntropyLoss
Understanding of smt32h7 series DMA and DMAMUX
Composition of applet code
nodejs_ fs. writeFile
Kotlin introductory notes (II) a brief introduction to kotlin functions
Lepton 无损压缩原理及性能分析
mysql安装配置以及创建数据库和表
2311. 小于等于 K 的最长二进制子序列
Hi Fun Summer, play SQL planner with starrocks!
LeetCode 31. Next spread
Greendao reported an error in qigsaw, could not init daoconfig
C form click event did not respond
【两个对象合并成一个对象】
Rebuild my 3D world [open source] [serialization-3] [comparison between colmap and openmvg]
【js 根据对象数组中的属性进行排序】
SMT32H7系列DMA和DMAMUX的一点理解
High performance spark_ Transformation performance
An article takes you into the world of cookies, sessions, and tokens