How to remove a single document from MongoDB using Go
Asked Answered
D

2

6

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

Desman answered 1/2, 2016 at 12:30 Comment(2)
Did you read the docs godoc.org/gopkg.in/mgo.v2#Collection.Remove ?Gimpel
@Alex Blex thanks man..Desman
P
8

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)
}
Pegues answered 2/2, 2016 at 8:21 Comment(0)
M
9

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

Muhammad answered 26/9, 2019 at 5:42 Comment(0)
P
8

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)
}
Pegues answered 2/2, 2016 at 8:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.