Search code examples
mongodbgomgo

How to remove a single document from MongoDB using Go


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


Solution

  • 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)
    }