After installing mongodb, we can use go to operate mongodb for happy CRUD

Install the Mogodb driver

$ go get github.com/mongodb/mongo-go-driver 
Copy the code

Connect the mongo

	// Set the client connection configuration
	clientOptions := options.Client().ApplyURI("mongodb://user:pwd@server:port/db")

	// Connect to MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)
	iferr ! =nil {
		log.Fatal(err)
	} else {
		fmt.Printf("client %#v \n", client) // client &mongo.Client{... }
	}
Copy the code

Check the connection

	// Check the connection
	err = client.Ping(context.TODO(), nil)
	iferr ! =nil {
		log.Fatal(err)
	} else {
		fmt.Println("Connected to MongoDB!")}Copy the code

Connected data set

Equivalent to a table in mysql

	/ / data set
	collection := client.Database("db").Collection("coder")
	fmt.Printf("collection %#v \n", collection) // collection &mongo.Collection{... }
Copy the code

Add a line of document

Equivalent to js db.coder. InsertOne ({})

	s1 := Coder{"Code guy 0.".35}
	insertResult, err := collection.InsertOne(context.TODO(), s1)
	iferr ! =nil {
		log.Fatal(err)
	}
	fmt.Println("Inserted a single document: ", insertResult.InsertedID) // ObjectID("5fe81819be51c1175cd95ba3")
Copy the code

Check with Robo 3T

Add multi-line documents

Equivalent to js db.coder. InsertMany ([… )

	// Insert multiple
      	s2 := Coder{"Code guy 1.".36}
	s3 := Coder{"Code guy 2.".37}
	coders := []interface{}{s2, s3}
	insertManyResult, err := collection.InsertMany(context.TODO(), coders)
	iferr ! =nil {
		log.Fatal(err)
	}
	fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs) // Inserted multiple documents: [ObjectID("5fe818a70bb1cc7b7b030fe7") ObjectID("5fe818a70bb1cc7b7b030fe8")]
Copy the code

Look for a

Equivalent to js bd.coder. Find (filter)

	filter := bson.D{{"name"."Code guy 0."}}
	var result Coder
	err = collection.FindOne(context.TODO(), filter).Decode(&result)
	iferr ! =nil {
		log.Fatal(err)
	}
	fmt.Printf("Found a single document: %+v\n", result)
Copy the code

Look for more

Db.coder.find ()

	// Query multiple
	// Pass the option to Find()
	findOptions := options.Find()
	findOptions.SetLimit(2)

	// Define a slice to store query results
	var results []*Coder

	// use bson.D{{}} as a filter to match all documents
	cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
	iferr ! =nil {
		log.Fatal(err)
	}

	// Finding multiple documents returns a cursor
	// Traversing the cursor allows us to decode one document at a time
	for cur.Next(context.TODO()) {
		// Create a value to decode a single document to that value
		var elem Coder
		err := cur.Decode(&elem)
		iferr ! =nil {
			log.Fatal(err)
		}
		results = append(results, &elem)
	}

	iferr := cur.Err(); err ! =nil {
		log.Fatal(err)
	}

	// Close the cursor when done
	cur.Close(context.TODO())

	fmt.Printf("Found multiple documents (array of pointers): %#v\n", results)

	for index, coder := range results {
		fmt.Printf("coder %v name %v age %v \n", index, coder.Name, coder.Age)
	}
Copy the code

update

The js equivalent of db.coder. Update (…)

	// Find filter
	filter := bson.D{{"name"."Code guy 0."}}
	/ / update
	update := bson.D{
		{"$inc", bson.D{
			{"age".1},
		}},
	}
	updateResult, err := collection.UpdateOne(context.TODO(), filter, update)
	iferr ! =nil {
		log.Fatal(err)
	}
	fmt.Printf("Matched %v documents and updated %v documents. \n", updateResult.MatchedCount, updateResult.ModifiedCount)
Copy the code

To delete a

Equivalent to js db.coder. DeleteOne (…)

	deleteResult1, err := collection.DeleteOne(context.TODO(), bson.D{{"name"."Code guy 0."}})
	iferr ! =nil {
		log.Fatal(err)
	}
	fmt.Printf("Deleted %v documents in the collection\n", deleteResult1.DeletedCount)
Copy the code

To delete multiple

Equivalent to js db.coder.drop()

	// Delete all
	deleteResult2, err := collection.DeleteMany(context.TODO(), bson.D{{}})
	iferr ! =nil {
		log.Fatal(err)
	}
	fmt.Printf("Deleted %v documents in the collection\n", deleteResult2.DeletedCount)
Copy the code