话说上一节我们说到MongoDB的基本使用,当命令行的操作我们熟悉了以后,就可以使用相关的Driver,也就是驱动程序进行相关编程语言的使用操作,因为在实际的开发过程中总归是要用编程语言来控制的,因此这篇文章我们介绍两个最常用的编程语言—Go&Java,来使用各自的驱动链接并操作MongoDB,Start!
1 都有哪些语言有MongoDB的Driver
诺,如图:
网络异常,图片无法展示
|
你以为只有这些吗?
太小看我们的工程师群体了,我们还有研究并开源的社区版本的Drivers,如Dart、Erlang、Kotlin等等
附上链接:www.mongodb.com/docs/driver…
2 Go连接MongoDB
2.1 添加依赖
go get go.mongodb.org/mongo-driver/mongo 复制代码
2.2 代码
main函数
package main import ( "context" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) var Coll *mongo.Collection func main() { //URL规则: //mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]] client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://127.0.0.1:27017")) if err != nil { panic(err) } defer func() { if err := client.Disconnect(context.TODO()); err != nil { panic(err) } }() Coll = client.Database("test").Collection("books") //InsertOne() //InsertMany() //FindOne() //FindAny() //UpdateOne() //UpdateAny() DeleteOne() } 复制代码
具体代码:
package main import ( "context" "encoding/json" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo/options" ) //InsertOne 添加一个 func InsertOne() { result, err := Coll.InsertOne( context.TODO(), bson.D{ {"type", "计算机"}, {"name", "《MongoDB教程》"}, {"price", 9.9}, {"vendor", bson.A{"JD", "TB"}}, }, ) if err != nil { panic(err) } fmt.Println(result) } //InsertMany 添加一批 func InsertMany() { docs := []interface{}{ bson.D{{"type", "计算机"}, {"name", "《Go教程》"}, {"price", 19.9}, {"vendor", bson.A{"JD", "TB"}}}, bson.D{{"type", "人文"}, {"name", "《人间词话》"}, {"price", 9.9}, {"vendor", bson.A{"PDD", "TB"}}}, bson.D{{"type", "计算机"}, {"name", "《Java教程》"}, {"price", 29.9}, {"vendor", bson.A{"JD", "TB", "PDD"}}}, bson.D{{"type", "计算机"}, {"name", "《Redis教程》"}, {"price", 19.9}, {"vendor", bson.A{"JD", "TB"}}}, } result, err := Coll.InsertMany(context.TODO(), docs) if err != nil { panic(err) } fmt.Println(result) } //FindOne 查找一个,多个符合条件的也返回一个 func FindOne() { var result bson.M err := Coll.FindOne(context.TODO(), bson.D{{"type", "计算机"}}).Decode(&result) if err != nil { panic(err) } jsonData, err := json.MarshalIndent(result, "", "") if err != nil { panic(err) } fmt.Printf("%s\n", jsonData) } //FindAny 查看多个 func FindAny() { var result bson.M //取前两条 cursor, err := Coll.Find(context.TODO(), bson.D{}, options.Find().SetLimit(2)) if err != nil { panic(err) } for cursor.Next(context.TODO()) { cursor.Decode(&result) jsonData, err := json.MarshalIndent(result, "", "") if err != nil { panic(err) } fmt.Printf("%s\n", jsonData) } } //UpdateOne 修改一个 func UpdateOne() { result, err := Coll.UpdateOne( context.TODO(), //修改条件 bson.D{{"price", 9.9}}, //修改结果 bson.D{{"$set", bson.D{{"price", 39.9}}}}, ) if err != nil { panic(err) } //修改文档的数量 fmt.Println(result.ModifiedCount) } //UpdateAny 修改符合条件的多个 func UpdateAny() { result, err := Coll.UpdateMany( context.TODO(), //修改条件 bson.D{{"price", 39.9}}, //修改结果 bson.D{{"$set", bson.D{{"price", 9.99}}}}, ) if err != nil { panic(err) } //修改文档的数量 fmt.Println(result.ModifiedCount) } //DeleteOne 删除一个 func DeleteOne() { result, err := Coll.DeleteOne( context.TODO(), bson.D{{"name", "《Redis教程》"}}, ) if err != nil { panic(err) } //删除文档的数量 fmt.Println(result.DeletedCount) } 复制代码
3 Java连接MongoDB
3.1 依赖
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.6.1</version> <exclusions> <exclusion> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-core</artifactId> </exclusion> <exclusion> <groupId>org.mongodb</groupId> <artifactId>bson</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-core</artifactId> <version>4.6.1</version> <exclusions> <exclusion> <groupId>org.mongodb</groupId> <artifactId>bson</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>bson</artifactId> <version>4.6.1</version> </dependency> 复制代码
3.2 代码
package org.ymx.sb_mongodb.cache; import com.mongodb.client.*; import com.mongodb.client.model.Filters; import com.mongodb.client.model.Updates; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.InsertManyResult; import com.mongodb.client.result.InsertOneResult; import com.mongodb.client.result.UpdateResult; import org.bson.Document; import org.bson.conversions.Bson; import java.util.ArrayList; import java.util.Arrays; import static com.mongodb.client.model.Filters.eq; public class MongoDBUtil { private String url = "mongodb://localhost:27017"; private MongoClient client; private MongoCollection<Document> collection; public void init() { // 注意,这里我们配置mongos服务信息即可 client = MongoClients.create(url); //获取数据库 MongoDatabase database = client.getDatabase("test"); // 获取集合 collection = database.getCollection("books"); } public void insertOne() { Document doc = new Document("type", "计算机") .append("name", "《JavaScript教程》") .append("price", 59.9) .append("vendor", Arrays.asList("JD", "TB")); InsertOneResult result = collection.insertOne(doc); System.out.println(result.getInsertedId()); } public void findOne() { Bson eq = eq("type", "计算机"); FindIterable<Document> find = collection.find(eq); Document first = find.first(); System.out.println(first); } public void insertMany() { ArrayList<Document> documents = new ArrayList<>(); Document doc1 = new Document("type", "历史") .append("name", "《人类简史》") .append("price", 69.9) .append("vendor", Arrays.asList("JD", "TB")); Document doc2 = new Document("type", "历史") .append("name", "《近代史》") .append("price", 29.9) .append("vendor", Arrays.asList("JD", "TB")); Document doc3 = new Document("type", "计算机") .append("name", "《Python教程》") .append("price", 59.9) .append("vendor", Arrays.asList("JD", "TB")); documents.add(doc1); documents.add(doc2); documents.add(doc3); InsertManyResult result = collection.insertMany(documents); System.out.println(result.getInsertedIds()); } public void updateOne() { Bson bson = Filters.eq("type", "计算机"); Bson bson1 = Updates.set("type", "科学"); UpdateResult result = collection.updateOne(bson, bson1); System.out.println(result.getModifiedCount()); } public void findMany() { FindIterable<Document> documents = collection.find(); documents.forEach(document -> { System.out.println(document); }); } public void deleteOne() { DeleteResult result = collection.deleteOne(eq("name", "《MongoDB教程》")); System.out.println(result.getDeletedCount()); } public static void main(String[] args) { MongoDBUtil util = new MongoDBUtil(); util.init(); //util.insertOne(); //util.findOne(); //util.insertMany(); //util.updateOne(); //util.findMany(); //util.deleteOne(); } } 复制代码
4 总结
本篇文章仅展示了不同的编程语言连接MongoDB中最常用的操作,当然MongoDB的可用操作不止这些,大家还可以利用官方文档进行深入的研究。
参考: