操作MongoDB
-
- 1、MongoDB概述
- 2、安装MongoDB数据库
- 3、安装MongoDB包
- 4、连接MongoDB
- 3、插入数据
- 5、更新数据
- 6、查询数据
- 7、删除数据
- 8、索引操作
- [9、事务(MongoDb 4.0+)](#9、事务(MongoDb 4.0+))
- [10、与 Express 结合示例](#10、与 Express 结合示例)
1、MongoDB概述
由于MongoDB数据库在JavaScript脚本环境中支持BSON对象(JSON对象的二进制形式)的存取,因此对于数据的存取的效率是非常高的。在MongoDB数据库中,将每一条等待插入的数据记录存储在内存中,因此,该数据库是一种非阻塞型数据库,在需要记载大量日志数据、实时测量数据或实时统计数据时,该数据库可以达到令人满意的效果。由于MongoDB数据库支持在查询语句内部使用JavaScript函数,也大大加强了它读取数据的能力。
MongoDB数据库中支持的数据类型:
| 数据类型 | 说明 | 数据使用示例 |
|---|---|---|
Array |
数组 | cardsInHand:[9,4,3] |
Boolean |
布尔类型,只允许true或false值 | hasBeenRead:false |
Code |
数据库内部可运行的一段JavaScript脚本代码 | new BSON.Code( 'function quotient(dividend, divisor){ return divisor == 0 ? 0:dividen / divisor;}'); |
Date |
当前日期和时间 | lastUpdated:new Date() |
DBRef |
数据库引用 | bestFriendId: new BSON.DBRef('users', friendObjectId) |
Integer |
整数值 | pageViews:50 |
Long |
长整数值 | starsInUniverse=new BSON.Long("100000000000000000"); |
Hash |
一个"键值/键名"形式的数据字典 | userName:{'first':'Sam', 'last':'Smith'} |
Null |
null值 | bestFriend: null |
ObjectID |
MongoDB数据库中用于索引对象的一个12字节的代码,其表现形式为一个24位的十六进制字符串 | |
String |
字符串 | fullName: 'Sam Smith' |
2、安装MongoDB数据库
可以在MongoDB官网(网址为http://www.mongodb.org/)上根据操作系统类型下载相应的MongoDB数据库安装包。在下载及解压缩后的安装包的bin文件夹中,包含了一系列可执行文件。其中用于运行数据库服务器的可执行文件名为mongod,用于运行与数据库服务器相连接的客户端的可执行文件名为mongo。
在运行数据库服务器之前,需要挑选磁盘中一个空的文件夹,在数据库服务器运行时将会在其中写入一些运行数据库服务器时所需使用的文件。
js
mongod -dbpath <用户挑选的磁盘文件夹名>
3、安装MongoDB包
当用户需要在Node.js应用程序中执行MongoDB数据库连接时,可以下载MongoDB包,在下载的包中包含了MongoDB本地驱动程序。可以使用如下所示的命令安装MongoDB包。
shell
npm install mongodb
在安装了MongoDB包后,可以使用如下所示的表达式来使用MongoDB模块。
js
const { MongoClient } = require("mongodb");
Node.js >= 16
MongoDB >= 4.x
4、连接MongoDB
js
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/
async function main() {
const client = new MongoClient(uri);
try {
await client.connect();
console.log("连接成功");
const db = client.db("testdb");
const collection = db.collection("users");
// 这里写你的操作
} finally {
await client.close();
}
}
main().catch(console.error);
js
连接成功
3、插入数据
插入单条:
js
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/
async function main() {
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db("testdb");
const collection = db.collection("users");
//插入单条数据
const result = await collection.insertOne({
name: "张三",
age: 25,
email: "123@123.com"
});
console.log(result);
} finally {
await client.close();
}
}
main().catch(console.error);
js
{
acknowledged: true,
insertedId: new ObjectId('69d1e8f5add3ecc5377bc361')
}
插入多条:
js
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/
async function main() {
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db("testdb");
const collection = db.collection("users");
//插入多条数据
const result = await collection.insertMany([
{ name: "李四", age: 30 },
{ name: "王五", age: 28 }
]);
console.log(result);
} finally {
await client.close();
}
}
main().catch(console.error);
js
{
acknowledged: true,
insertedCount: 2,
insertedIds: {
'0': new ObjectId('69d1e93ef05ee234c2511e27'),
'1': new ObjectId('69d1e93ef05ee234c2511e28')
}
}
5、更新数据
更新单条:
js
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/
async function main() {
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db("testdb");
const collection = db.collection("users");
//更新单条数据
const result = await collection.updateOne(
{name: "张三"},
{$set: {age: 260}}
);
console.log(result);
} finally {
await client.close();
}
}
main().catch(console.error);
json
{
acknowledged: true,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0,
matchedCount: 1
}
更新多条:
js
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/
async function main() {
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db("testdb");
const collection = db.collection("users");
//更新多条数据
const result = await collection.updateMany(
{age: {$lt: 30}},
{$inc: {age: 1}}
);
console.log(result);
} finally {
await client.close();
}
}
main().catch(console.error);
json
{
acknowledged: true,
modifiedCount: 2,
upsertedId: null,
upsertedCount: 0,
matchedCount: 2
}
6、查询数据
查询所有:
js
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/
async function main() {
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db("testdb");
const collection = db.collection("users");
//查询所有数据
const result = await collection.find().toArray();
console.log(result);
} finally {
await client.close();
}
}
main().catch(console.error);
json
[
{
_id: new ObjectId('69d1e8e60a6eabb1203b66d5'),
name: '张三',
age: 260,
email: '123@123.com'
},
{
_id: new ObjectId('69d1e8f5add3ecc5377bc361'),
name: '张三',
age: 26,
email: '123@123.com'
},
{
_id: new ObjectId('69d1e93ef05ee234c2511e27'),
name: '李四',
age: 30
},
{
_id: new ObjectId('69d1e93ef05ee234c2511e28'),
name: '王五',
age: 29
}
]
条件查询
js
const result = await collection.find({name: "张三"}).toArray();
console.log(result);
json
[
{
_id: new ObjectId('69d1e8e60a6eabb1203b66d5'),
name: '张三',
age: 260,
email: '123@123.com'
},
{
_id: new ObjectId('69d1e8f5add3ecc5377bc361'),
name: '张三',
age: 26,
email: '123@123.com'
}
]
高级查询:
js
const result = await collection.find(
{age: {$gt: 25}}
).toArray();
console.log(result);
json
[
{
_id: new ObjectId('69d1e8e60a6eabb1203b66d5'),
name: '张三',
age: 260,
email: '123@123.com'
},
{
_id: new ObjectId('69d1e8f5add3ecc5377bc361'),
name: '张三',
age: 26,
email: '123@123.com'
},
{
_id: new ObjectId('69d1e93ef05ee234c2511e27'),
name: '李四',
age: 30
},
{
_id: new ObjectId('69d1e93ef05ee234c2511e28'),
name: '王五',
age: 29
}
]
7、删除数据
删除单条:
js
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/
async function main() {
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db("testdb");
const collection = db.collection("users");
//删除单条数据
const result = await collection.deleteOne({name: "李四"});
console.log(result);
} finally {
await client.close();
}
}
main().catch(console.error);
json
{ acknowledged: true, deletedCount: 1 }
删除多条:
js
const result = await collection.deleteMany({age : {$gt: 50}});
console.log(result);
json
{ acknowledged: true, deletedCount: 1 }
8、索引操作
创建索引:
js
const result = await collection.createIndex({email: 1}, {unique: true});
console.log(result);
email_1
查看索引:
js
const indexes = await collection.indexes();
console.log(indexes);
js
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { email: 1 }, name: 'email_1', unique: true }
]
9、事务(MongoDb 4.0+)
js
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017"; // 本地
// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/
async function main() {
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db("testdb");
const collection = db.collection("users");
const session = client.startSession();
try {
session.startTransaction();
await collection.insertOne({ name: "事务测试" }, { session });
await session.commitTransaction();
} catch (e) {
await session.abortTransaction();
} finally {
session.endSession();
}
} finally {
await client.close();
}
}
main().catch(console.error);
10、与 Express 结合示例
js
app.get("/users", async (req, res) => {
const users = await collection.find().toArray();
res.json(users);
});