Go MongoDB官方数据库驱动之增删改查
程序员文章站
2022-03-07 10:37:18
"One" "Two" ......
package main import ( "context" "fmt" "log" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) // trainer type is used for later type trainer struct { name string age int city string } func main() { // set client options clientoptions := options.client().applyuri("mongodb://localhost:27017") // connect to mongodb client, err := mongo.connect(context.todo(), clientoptions) if err != nil { log.fatal(err) } // check the connection err = client.ping(context.todo(), nil) if err != nil { log.fatal(err) } fmt.println("connected to mongodb!") // get collection collection := client.database("test").collection("trainers") ash := trainer{"ash", 10, "pallet town"} misty := trainer{"misty", 10, "cerulean city"} brock := trainer{"brock", 15, "pewter city"} // insert insertresult, err := collection.insertone(context.todo(), ash) if err != nil { log.fatal(err) } fmt.println("inserted a single document: ", insertresult.insertedid) trainers := []interface{}{misty, brock} insertmanyresult, err := collection.insertmany(context.todo(), trainers) if err != nil { log.fatal(err) } fmt.println("inserted multiple documents: ", insertmanyresult.insertedids) // update filter := bson.d{{"name", "ash"}} update := bson.d{ {"$inc", bson.d{ {"age", 1}, }}, } updateresult, err := collection.updateone(context.todo(), filter, update) if err != nil { log.fatal(err) } fmt.printf("matched %v documents and updated %v documents.\n", updateresult.matchedcount, updateresult.modifiedcount) // search var result trainer err = collection.findone(context.todo(), filter).decode(&result) if err != nil { log.fatal(err) } fmt.printf("found a single document: %+v\n", result) findoptions := options.find() findoptions.setlimit(5) var results []*trainer cur, err := collection.find(context.todo(), bson.d{{}}, findoptions) if err != nil { log.fatal(err) } for cur.next(context.todo()) { var elem trainer err := cur.decode(&elem) if err != nil { log.fatal(err) } results = append(results, &elem) } if err := cur.err(); err != nil { log.fatal(err) } cur.close(context.todo()) fmt.printf("found multiple documents (array of pointers): %+v\n", results) // delete deleteresult, err := collection.deletemany(context.todo(), bson.d{{}}) if err != nil { log.fatal(err) } fmt.printf("deleted %v documents in the trainers collection\n", deleteresult.deletedcount) }