引言

MongoDB是流行的文档型NoSQL数据库。本文介绍MongoDB的基础和实战应用。

一、MongoDB基础

1.1 基本概念

1
2
3
4
Database(数据库)
Collection(集合)→ Table(表)
Document(文档) → Row(行)
Field(字段) → Column(列)

1.2 数据类型

1
2
3
4
5
6
7
8
9
10
11
12
{
"_id": ObjectId("..."),
"name": "Alice", // String
"age": 25, // Number
"active": true, // Boolean
"hobbies": ["读书", "旅游"], // Array
"address": { // Object
"city": "Beijing",
"zip": "100000"
},
"created_at": ISODate("2023-07-30") // Date
}

二、CRUD操作

2.1 插入文档

1
2
3
4
5
6
7
8
9
10
11
12
// 插入单个
db.users.insertOne({
name: "Alice",
age: 25,
email: "alice@example.com"
});

// 插入多个
db.users.insertMany([
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
]);

2.2 查询文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 查询所有
db.users.find();

// 条件查询
db.users.find({ age: { $gte: 25 } });

// 投影
db.users.find({}, { name: 1, age: 1, _id: 0 });

// 排序和限制
db.users.find().sort({ age: -1 }).limit(10);

// 统计
db.users.countDocuments({ age: { $gte: 25 } });

2.3 更新文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 更新单个
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } }
);

// 更新多个
db.users.updateMany(
{ age: { $lt: 30 } },
{ $inc: { age: 1 } }
);

// 替换文档
db.users.replaceOne(
{ name: "Alice" },
{ name: "Alice", age: 26, email: "alice@new.com" }
);

2.4 删除文档

1
2
3
4
5
6
7
8
// 删除单个
db.users.deleteOne({ name: "Alice" });

// 删除多个
db.users.deleteMany({ age: { $lt: 18 } });

// 删除所有
db.users.deleteMany({});

三、索引

3.1 创建索引

1
2
3
4
5
6
7
8
9
10
11
// 单字段索引
db.users.createIndex({ email: 1 });

// 复合索引
db.users.createIndex({ name: 1, age: -1 });

// 唯一索引
db.users.createIndex({ email: 1 }, { unique: true });

// 文本索引
db.articles.createIndex({ content: "text" });

3.2 查看索引

1
2
3
4
5
// 查看所有索引
db.users.getIndexes();

// 删除索引
db.users.dropIndex("email_1");

四、聚合查询

1
2
3
4
5
6
7
8
9
10
11
12
13
db.orders.aggregate([
// 匹配
{ $match: { status: "completed" } },
// 分组
{ $group: {
_id: "$user_id",
total: { $sum: "$amount" }
}},
// 排序
{ $sort: { total: -1 } },
// 限制
{ $limit: 10 }
]);

五、Java使用MongoDB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 连接MongoDB
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("users");

// 插入
Document doc = new Document("name", "Alice")
.append("age", 25);
collection.insertOne(doc);

// 查询
FindIterable<Document> docs = collection.find(Filters.eq("name", "Alice"));

// 更新
collection.updateOne(
Filters.eq("name", "Alice"),
Updates.set("age", 26)
);

// 删除
collection.deleteOne(Filters.eq("name", "Alice"));

总结

MongoDB核心:

  1. 文档存储:灵活的JSON格式
  2. CRUD操作:简单易用的API
  3. 索引:提升查询性能
  4. 聚合:强大的数据分析能力

参考资料