这篇文章主要介绍了使用GO操作MongoDB,包括安装MongoDB驱动程序连接mongodb的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
1.安装 MongoDB Go 驱动程序
MongoDB Go Driver 由几个包组成。如果您只是使用 go get,则可以使用以下命令安装驱动程序:
go get github.com/mongodb/mongo-go-driver
这个输出可能看起来像一个警告,说明类似于 package github.com/mongodb/mongo-go-driver: no Go files in (…)。这是预期的输出。
如果您使用 govendor 包管理器,则需要使用以下命令安装主 mongo 包以及 bson 和 mongo/options 包:
govendor fetch github.com/mongodb/mongo-go-driver/mongo govendor fetch go.mongodb.org/mongo-driver/bson govendor fetch go.mongodb.org/mongo-driver/mongo/options
2.设置连接
导入 MongoDB Go 驱动程序后,我们可以使用 Client.Connect(context) 连接到 MongoDB 部署。我们需要设置一个新客户端,我们需要在设置客户端时传递 mongo 数据库的 URI。然后我们只需要使用上下文调用 client.Connect(context),这将建立我们的连接。
以下代码为我们建立了一个连接:
//Set up a context required by mongo.Connect
ctx, cancel := context.WithTimeout(context.Background(), 10\*time.Second)
//To close the connection at the end
defer cancel()
//We need to set up a client first
//It takes the URI of your database
client, error := mongo.NewClient(options.Client().ApplyURI("your\_database\_uri"))
if error != nil {
log.Fatal(err)
}
//Call the connect function of client
error = client.Connect(ctx)
//Checking the connection
error = client.Ping(context.TODO(), nil)
fmt.Println("Database connected")
3.在 Go 中使用 BSON 对象
MongoDB 中的 JSON 文档存储在称为 BSON(二进制编码 JSON)的二进制表示中。与将 JSON 数据存储为简单字符串和数字的其他数据库不同,BSON 编码扩展了 JSON 表示以包括其他类型,例如 int、long、date、floating point 和 decimal128。这使得应用程序更容易可靠地处理、排序和比较数据。 Go Driver 有两个表示 BSON 数据的类型:D 类型和 Raw 类型。
D 系列类型用于使用本机 Go 类型简洁地构建 BSON 对象。这对于构造传递给 MongoDB 的命令特别有用。 D 系列包括四种类型:
- D:BSON 文档。这种类型应该在顺序很重要的情况下使用,例如 MongoDB 命令。
- M:无序映射。它与 D 相同,只是它不保持顺序。
- A:一个 BSON 数组。
- E:D 中的单个元素。
这是一个使用 D 类型构建的过滤器文档的示例,可用于查找名称字段与 Alice 或 Bob 匹配的文档:
bson.D{{
"name",
bson.D{{
"$in",
bson.A{"Alice", "Bob"}
}}
}}
4. CRUD 操作
对于 CRUD 和其他操作,我们需要使用集合对象,我们可以通过引用数据库中各自的集合来创建它,例如:
BooksCollection := client.Database("test").Collection("books")
插入
对于创建,我们可以将 collection.InsertOne() 用于单个条目,也可以使用 collection.InsertMany() 来接收对象切片。
/\*\*
\* Create - Adding a new book
\* res -\> the insert command returns the inserted id of the oject
\*/
res, err := BooksCollection.InsertOne(ctx, bson.M{"name": "The Go Language", "genre": "Coding", "authorId": "4"})
if err != nil {
log.Fatal(err)
}
在 collection.InsertOne() 中,我们可以通过 bson.M{} 传递一个字符串对象,或者我们可以创建一个我们各自类型结构的对象并传递该对象。
阅读
为了查找文档,我们需要一个过滤文档以及一个指向可以将结果解码成的值的指针。要查找单个文档,请使用 collection.FindOne()。此方法返回一个可以解码为值的结果。过滤器对象指定我们要查找的内容。
filter := bson.D{{"name", "Book 1"}}
// create a value into which the result can be decoded
var result bookType
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found a single Book: %+v\n", result)
要查找多个文档,请使用 collection.Find()。此方法返回一个光标。游标提供了一个文档流,我们可以通过它一次迭代和解码一个。一旦游标用尽,我们应该关闭游标。
cur, error := BooksCollection.Find(ctx, bson.D{{}})
var allbooks []\*bookType
//Loops over the cursor stream and appends to result array
for cur.Next(context.TODO()) {
var booksResultHolder bookType
err := cur.Decode(&bookResultHolder)
if err != nil {
log.Fatal(err)
}
allbooks = append(allbooks, &booksResultHolder)
}
//dont forget to close the cursor
defer cur.Close(context.TODO())
// Loop over the result array and perform whatever required
for \_, element := range allbooks {
book := \*element
fmt.Println(book)
}
更新
collection.UpdateOne() 方法允许您更新单个文档。它需要一个过滤文档来匹配数据库中的文档,并需要一个更新文档来描述更新操作。这些可以按照我们在阅读时制作过滤器对象的方式构建。
/\*\*
\* Update
\* Collection has functions like UpdateOne and UpdateMany
\* Returns the Matched and Modified Count
\*/
filter := bson.D{{"name", "Book 1"}}
// Need to specify the mongodb output operator too
newName := bson.D{
{"$set", bson.D{
{"name", "Updated Name of Book 1"},
}},
}
res, err := BooksCollection.UpdateOne(ctx, filter, newName)
if err != nil {
log.Fatal(err)
}
updatedObject := \*res
fmt.Printf("The matched count is : %d, the modified count is : %d", updatedObject.MatchedCount, updatedObject.ModifiedCount)
删除
最后,我们可以使用 collection.DeleteOne() 或 collection.DeleteMany() 删除文档。在这里,我们可以传递 nil 作为过滤器参数,它将匹配集合中的所有文档或任何其他特定参数。我们还可以使用collection.Drop()删除整个集合。
filter = bson.D{{"name", "Updated Name of Book 2"}}
deleteResult, error := BooksCollection.DeleteOne(ctx, filter)
后续步骤
本教程的源代码可以在这里找到。
MongoDB Go 驱动程序的文档可在GoDoc上找到。您可能对有关使用聚合或交易的文档特别感兴趣。
希望本教程对您来说更简单,祝大家编码愉快!
