0、简介
官网:https://docs.mongodb.com
中文文档:https://www.mongodb.org.cn
操作文档:https://www.qikegu.com/docs/3283
其他替代:
DynamoDB:AWS
SequoiaDB:巨杉数据库
1、安装、
安装地址:
https://www.mongodb.com/try/download/community-kubernetes-operator
https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-5.0.31-rc0-signed.msi
注:新的版本客户端 需要独立安装
添加环境变量
然后在 cmd 中输入:
mongo 进入命令行
退出是 : exit
2、基础操作
1、库的操作
//显示
show databases;
//删除,只有插入数据后才可 进行删除
> use mycollection
switched to db mydb
> db.dropDatabase();
//切换库,不用建,可以直接插入数据
use mycollection
2、集合(Collection)的操作
//插入数据(插入数据的时候就会建立文档)
> db.mycollection.insertOne({name: "John", age: 30});
{
"acknowledged" : true,
"insertedId" : ObjectId("60b8d3a1d9a8b7f789000001")
}
//查询当前有哪些 集合
show collections;
//删除集合
> db.mycollection.drop();
true
3、文档的操作
//插入数据
> db.mycollection.insertOne({name: "John", age: 30});
{
"acknowledged" : true,
"insertedId" : ObjectId("60b8d3a1d9a8b7f789000001")
}
//插入多条数据
> db.users.insertMany([
{
"username": "bob",
"email": "bob@example.com",
"password": "password456"
},
{
"username": "carol",
"email": "carol@example.com",
"password": "789abc"
}
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("60b8d6a1d9a8b7f789000003"),
ObjectId("60b8d6a1d9a8b7f789000004")
]
}
//查询
> db.users.find();
//查询指定 文档
> db.users.find({username: "alice"});
{ "_id" : ObjectId("60b8d5a1d9a8b7f789000002"), "username" : "alice", "email" : "alice@example.com", "password" : "secret123" }
//更新文档
> db.users.updateOne({username: "alice"}, {$set: {password: "newsecret"}});
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.users.updateMany({}, {$set: {email: {$concat: [ "$email", "test"]}}});
{
"acknowledged" : true,
"matchedCount" : 3,
"modifiedCount" : 3
}
//删除文档
> db.users.deleteOne({username: "alice"});
{ "acknowledged" : true, "deletedCount" : 1 }
//deleteMany方法用于删除所有符合条件的文档。例如,删除所有password以secret开头的文档:
> db.users.deleteMany({password: /^secret/});
{ "acknowledged" : true, "deletedCount" : 0 }
3、建立时间索引,按时间进行查询
添加测试数据
db.data.insertMany([
{ timestamp: ISODate("2025-01-01T10:00:00Z"), value: "Test Data 1" },
{ timestamp: ISODate("2025-01-01T12:00:00Z"), value: "Test Data 2" },
{ timestamp: ISODate("2025-01-01T14:00:00Z"), value: "Test Data 3" },
{ timestamp: ISODate("2025-01-02T08:00:00Z"), value: "Test Data 4" },
{ timestamp: ISODate("2025-01-02T10:00:00Z"), value: "Test Data 5" }
]);
添加索引
db.data.createIndex({ timestamp: 1 })
查询
db.data.find({
timestamp: {
$gte: ISODate("2025-01-01T00:00:00Z"),
$lt: ISODate("2025-01-02T00:00:00Z")
}
})
db.data.find().sort({ timestamp: 1 })
db.data.find().sort({ timestamp: -1 })