How to delete one document from MongoDB using Go

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

+5
source share
2 answers

The following example shows how to delete a document using the name"Foo Bar" from the collection of peoplethe database teston localhostit uses of the API: Remove()

// 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)
}
+7
source

MongoDB officially supports golang. Here is an example of removing 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

0
source

Source: https://habr.com/ru/post/1626852/


All Articles