引言
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", "age": 25, "active": true, "hobbies": ["读书", "旅游"], "address": { "city": "Beijing", "zip": "100000" }, "created_at": ISODate("2023-07-30") }
|
二、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
| 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核心:
- 文档存储:灵活的JSON格式
- CRUD操作:简单易用的API
- 索引:提升查询性能
- 聚合:强大的数据分析能力
参考资料