在Go语言中,可以使用MongoDB官方提供的go-mongo-driver库来进行文档管理操作。下面介绍一些常用的文档管理操作。
插入文档
可以使用InsertOne()或者InsertMany()函数向集合中插入一个或多个文档:
// 插入单个文档 doc := bson.M{“name”: “Alice”, “age”: 20} result, err := collection.InsertOne(context.Background(), doc)
// 插入多个文档 docs := []interface{}{
bson.M{"name": "Bob", "age": 25},
bson.M{"name": "Charlie", "age": 30},
} result, err := collection.InsertMany(context.Background(), docs)
更新文档
可以使用UpdateOne()或者UpdateMany()函数来更新一个或多个符合条件的文档:
filter := bson.M{“name”: “Alice”} update := bson.M{“$set”: bson.M{“age”: 21}} result, err := collection.UpdateOne(context.Background(), filter, update)
删除文档
可以使用DeleteOne()或者DeleteMany()函数来删除一个或多个符合条件的文档:
filter := bson.M{“name”: “Bob”} result, err := collection.DeleteOne(context.Background(), filter)
查询单个文档
可以使用FindOne()函数来查询符合条件的第一个文档:
filter := bson.M{“name”: “Alice”} var result bson.M err = collection.FindOne(context.Background(), filter).Decode(&result)
查询多个文档
可以使用Find()函数来查询符合条件的所有文档,并返回游标对象。然后通过游标对象遍历每个文档:
filter := bson.M{“age”: bson.M{“$gt”: 20}} cur, err := collection.Find(context.Background(), filter) defer cur.Close(context.Background()) for cur.Next(context.Background()) {
var result bson.M
err := cur.Decode(&result)
}
其中,$gt表示大于的意思。
上述是一些常用的MongoDB文档管理操作,还有更多高级操作请参考官方文档。