启动 mongodb
1
docker run -it --rm -p 27017:27017 --name mongodb -e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=123456 mongo:4.4
mongo_exp1.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"time"
)
type testData struct {
Name string `json:"name" bson:"name"`
Value string `json:"value" bson:"name"`
}
func main() {
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://127.0.0.1:27017"),
&options.ClientOptions{Auth: &options.Credential{
AuthMechanism: "",
AuthMechanismProperties: nil,
AuthSource: "",
Username: "root",
Password: "123456",
PasswordSet: true,
}})
if err != nil {
log.Fatal(err)
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(ctx)
testDatabase := client.Database("testdb")
testCollection := testDatabase.Collection("tests")
td := testData{
Name: "InsertTestName1",
Value: "InsertTetValue1",
}
if podcastResult, err := testCollection.InsertOne(ctx, td); err != nil {
log.Fatal(err)
} else {
fmt.Println(podcastResult)
}
if cursor, err := testCollection.Find(ctx, bson.D{}); err != nil {
log.Fatal(err)
} else {
for cursor.Next(ctx) {
var od testData
if err = cursor.Decode(&od); err != nil {
log.Fatal(err)
} else {
fmt.Printf("%s : %s\n", od.Name, od.Value)
}
}
}
}
程序输出
&{ObjectID("5f8fb0b3022b456b712e61e0")}
InsertTestName1 : InsertTetValue1
shell
登录 mongodb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ mongo --host 127.0.0.1 --port 27017 -u root -p 123456
> use testdb;
switched to db testdb
> db.tests.find();
{ "_id" : ObjectId("5f8fb0b3022b456b712e61e0"), "name" : "InsertTestName1", "value" : "InsertTetValue1" }
> db.tests.find().pretty();
{
"_id" : ObjectId("5f8fb0b3022b456b712e61e0"),
"name" : "InsertTestName1",
"value" : "InsertTetValue1"
}