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
Use delete operations to remove data from MongoDB. Delete operations consist of the following methods: DeleteOne() , which deletes the first document that matches the filter. DeleteMany() , which deletes all documents that match the filter.
MongoDB's remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag. deletion criteria − (Optional) deletion criteria according to documents will be removed.
By default, remove() removes all documents that match the query expression. Specify the justOne option to limit the operation to removing a single document. To delete a single document sorted by a specified order, use the findAndModify() method.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With