Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a single document from MongoDB using Go

Tags:

mongodb

go

mgo

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

like image 670
Arjun Ajith Avatar asked Feb 01 '16 12:02

Arjun Ajith


People also ask

How do I delete a document in MongoDB Golang?

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.

Which method is used to delete the document in MongoDB?

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.

Which of the following command is used to delete a single document in MongoDB?

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.


1 Answers

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)
}
like image 102
chridam Avatar answered Sep 19 '22 23:09

chridam