“This is the 19th day of my participation in the First Challenge 2022, for more details: First Challenge 2022”.

4.3.5 clustering

Similar to:

select by_user, count(*) from mycol group by by_user

To viewAggregateThe source of the

$sumExample:

  • Define maximum time
opts := options.Aggregate().SetMaxTime(2 * time.Second)
Copy the code
  • Define a query statement

Divided by the major field, each sum changes to 1

groupStage := bson.D{
	{"$group", bson.D{
		{"_id"."$major"},
		{"sum", bson.D{
			{"$sum".1}}},}}},Copy the code
  • The query
result, err := Collection.Aggregate(context.TODO(), mongo.Pipeline{groupStage}, opts)
Copy the code
  • Assignment. Note that the type can be defined by itself or used directlybson.M
var results []bson.M
iferr = result.All(context.TODO(), &results); err ! =nil {
	log.Fatal(err)
}
fmt.Printf("results : %+v\n", results)
Copy the code

$avgexample

  • Define a filter condition

Calculate the average age field for each major

groupStage := bson.D{{"$group",bson.D{{"_id"."$major"}, {"ageAvg",bson.D{{"$avg"."$age"}}},}}},Copy the code

The databaseThe results of

Example $min

Find the minimum age for each group with major as the group

groupStage := bson.D{{"$group",bson.D{{"_id"."$major"}, {"minAvg",bson.D{{"$min"."$age"}}}}}}
Copy the code

5. Update to update

5.1 Updating a Single Item

The first one is filter, which updates are selected, and the second one is the updated stuff that’s passed in, to be passed$set

res, err := Collection.UpdateOne(context.TODO(), bson.M{"name": "FanOne1"}, bson.M{"$set": bson.M{"age": 111}})
Copy the code
  • The results of

5.2 Updating Multiple Files

UpdateMany

Find the field Major for BigData and change age to 111.

res, err := Collection.UpdateMany(context.TODO(), bson.M{"major": "Big Data"}, bson.M{"$set": bson.M{"age": 111}})
Copy the code
  • The results of

6. Delete the delete

6.1 Deleting a Single Item

res, err := Collection.DeleteOne(context.TODO(), bson.M{"name": "FanOne0"})
iferr ! =nil {
	log.Fatal(err)
}
fmt.Printf("result : %+v\n", res)
Copy the code

6.2 Deleting Multiple Entries

res, err := Collection.DeleteMany(context.TODO(), bson.M{"major": "CS"})
iferr ! =nil {
	log.Fatal(err)
}
fmt.Printf("result : %+v\n", res)
Copy the code