如何使用Go从MongoDB中删除单个文档

huangapple go评论90阅读模式
英文:

How to remove a single document from MongoDB using Go

问题

你好!以下是你要翻译的内容:

我是Go语言和MongoDB的新手。
如何从MongoDB的集合中删除一个由"name"标识的单个文档?
提前感谢!

英文:

I am new in golang and MongoDb.
How can I delete a single document identified by "name" from a collection in MongoDB?
Thanks in Advance

答案1

得分: 8

以下是代码的中文翻译:

下面的示例演示了如何从localhost上的test数据库的people集合中删除一个名为“Foo Bar”的文档,它使用API中的**Remove()**方法:

// 获取会话
session, err := mgo.Dial("localhost")
if err != nil {
    fmt.Printf("连接失败 %v\n", err)
    os.Exit(1)
}
defer session.Close()

// 每次访问都进行错误检查
session.SetSafe(&mgo.Safe{})

// 获取集合
collection := session.DB("test").C("people")

// 删除记录
err = collection.Remove(bson.M{"name": "Foo Bar"})
if err != nil {
    fmt.Printf("删除失败 %v\n", err)
    os.Exit(1)
}
英文:

The following example demonstrates how to delete a single document with the name "Foo Bar" from a people collection in test database on localhost, it uses the Remove() method from the API:

// Get session
session, err := mgo.Dial("localhost")
if err != nil {
	fmt.Printf("dial fail %v\n", err)
	os.Exit(1)
}
defer session.Close()

// Error check on every access
session.SetSafe(&mgo.Safe{})

// Get collection
collection := session.DB("test").C("people")

// Delete record
err = collection.Remove(bson.M{"name": "Foo Bar"})
if err != nil {
	fmt.Printf("remove fail %v\n", err)
	os.Exit(1)
}

答案2

得分: 6

MongoDB官方支持golang。这里是一个从MongoDB中删除项目的示例:

// 假设您已经设置了MongoDB客户端
collection := client.Database("database_name").Collection("collection_hero")

deleteResult, _ := collection.DeleteOne(context.TODO(), bson.M{"_id": 
primitive.ObjectIDFromHex("_id")})
if deleteResult.DeletedCount == 0 {
    log.Fatal("删除一个英雄时出错", err)
}
return deleteResult.DeletedCount

了解更多信息,请访问:https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial

英文:

MongoDB officially supports golang. Here is a demostration of deleting an item from MongoDB:

// Assuming you've setup your mongoDB client
collection := client.Database("database_name").Collection("collection_hero")

deleteResult, _ := collection.DeleteOne(context.TODO(), bson.M{"_id": 
primitive.ObjectIDFromHex("_id")})
if deleteResult.DeletedCount == 0 {
    log.Fatal("Error on deleting one Hero", err)
}
return deleteResult.DeletedCount

For more information visit: https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial

huangapple
  • 本文由 发表于 2016年2月1日 20:30:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/35130590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定