Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Go 드라이버
/

문서 삭제

이 가이드에서는 삭제 작업을 사용하여 MongoDB 컬렉션에서 문서를 제거하는 방법에 대해 설명합니다.

이 가이드의 예시에서는 다음 Book 구조체를 books 컬렉션의 문서 모델로 사용합니다.

type Book struct {
Title string
Author string
Length int32
}

이 가이드의 예시를 실행하려면 다음 스니펫을 사용하여 샘플 데이터를 db.books 컬렉션에 로드합니다.

coll := client.Database("db").Collection("books")
docs := []interface{}{
Book{Title: "Atonement", Author: "Ian McEwan", Length: 351},
Book{Title: "My Brilliant Friend", Author: "Elena Ferrante", Length: 331},
Book{Title: "Lucy", Author: "Jamaica Kincaid", Length: 103},
Book{Title: "Outline", Author: "Rachel Cusk", Length: 258},
}
result, err := coll.InsertMany(context.TODO(), docs)

각 문서에는 각 문서의 title, author, length 필드에 해당하는 제목, 저자 및 페이지 길이가 포함된 책에 대한 설명이 포함되어 있습니다.

존재하지 않는 데이터베이스 및 collection

쓰기 작업을 수행할 때 필요한 데이터베이스 및 collection이 없는 경우 서버는 이를 암시적으로 생성합니다.

삭제 작업을 사용하여 MongoDB에서 데이터를 제거합니다. 삭제 작업은 다음 메서드로 구성됩니다.

  • DeleteOne()은 필터와 일치하는 첫 번째 문서를 삭제합니다.

  • DeleteMany()는 필터와 일치하는 모든 문서를 삭제합니다.

DeleteMany() 메서드를 실행할 때 한 문서가 필터와 일치하면 DeleteOne() 메서드를 실행하는 것과 동일합니다.

DeleteOne()DeleteMany() 메서드에서는 일치시킬 문서를 지정하는 Context 유형과 non-nil 쿼리 필터를 전달해야 합니다.

둘 다 선택적으로 DeleteOptions 유형을 세 번째 매개 변수로 사용하며, 이는 삭제 작업을 구성하는 데 사용할 수 있는 옵션입니다. DeleteOptions를 지정하지 않으면 드라이버는 각 옵션의 기본값을 사용합니다.

DeleteOptions 유형을 사용하면 다음 방법으로 옵션을 구성할 수 있습니다.

메서드
설명

SetHint()

The index to use to scan for documents to delete.
Default: nil

SetCollation()

The type of language collation to use when sorting results.
Default: nil

DeleteOne()DeleteMany() 메서드는 DeleteResult 유형을 반환합니다. 이 유형에는 삭제된 문서 수를 나타내는 DeletedCount 속성이 포함되어 있습니다. 필터와 일치하는 문서가 없으면 문서가 삭제되지 않고 DeletedCount0이 됩니다.

다음 예에서는 DeleteMany() 메서드를 사용하여 작업을 수행합니다.

  • length300보다 큰 문서를 일치시키고 삭제합니다.

  • _id를 인덱스로 사용하도록 메서드에 지시합니다.

filter := bson.D{{"length", bson.D{{"$gt", 300}}}}
opts := options.Delete().SetHint(bson.D{{"_id", 1}})
result, err := coll.DeleteMany(context.TODO(), filter, opts)
if err != nil {
panic(err)
}
fmt.Printf("Number of documents deleted: %d\n", result.DeletedCount)
Number of documents deleted: 2

앞에 설명한 예에서 DeleteMany() 대신 DeleteOne() 메서드를 사용한 경우 드라이버는 일치하는 두 문서 중 첫 번째 문서를 삭제합니다.

참고

설정 예시

이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습하려면 MongoClient 만들기 가이드를 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된 sample_restaurants 데이터베이스의 restaurants 컬렉션도 사용합니다. Atlas 시작하기 가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.

다음 예시 restaurants 컬렉션 에서 기존 문서 찾아 삭제하는 완전히 실행 가능한 파일 입니다.

// Deletes a document from a collection by using the Go driver
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
// Defines a Restaurant struct as a model for documents in the "restaurants" collection
type Restaurant struct {
ID bson.ObjectID `bson:"_id"`
Name string `bson:"name"`
Cuisine string `bson:"cuisine,omitempty"`
Address interface{} `bson:"address,omitempty"`
Borough string `bson:"borough,omitempty"`
Grades []interface{} `bson:"grades,omitempty"`
}
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/ko-kr/docs/drivers/go/current/connect/mongoclient/#environment-variable")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll := client.Database("sample_restaurants").Collection("restaurants")
filter := bson.D{{"name", "New Corner"}}
// Deletes the first document that has a "name" value of "New Corner"
result, err := coll.DeleteOne(context.TODO(), filter)
// Prints a message if any errors occur during the operation
if err != nil {
panic(err)
}
// Prints the number of deleted documents
fmt.Printf("Documents deleted: %d\n", result.DeletedCount)
// When you run this file for the first time, it prints output similar to the following:
// Documents deleted: 1
}
Documents deleted: 1

참고

설정 예시

이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습하려면 MongoClient 만들기 가이드를 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된 sample_restaurants 데이터베이스restaurants 컬렉션도 사용합니다. Atlas 시작하기 가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.

다음 예시 restaurants 컬렉션 에 대해 다음 조치를 수행하는 완전히 실행 가능한 파일 입니다.

  • cuisine 필드 값이 German 이고 borough 필드 값이 Queens인 문서를 일치하고 삭제합니다.

  • 일치하는 모든 문서 삭제

// Deletes multiple documents from a collection by using the Go driver
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
// Defines a Restaurant struct as a model for documents in the "restaurants" collection
type Restaurant struct {
ID bson.ObjectID `bson:"_id"`
Name string `bson:"name"`
Borough string `bson:"borough"`
Cuisine string `bson:"cuisine"`
}
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/ko-kr/docs/drivers/go/current/connect/mongoclient/#environment-variable")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll := client.Database("sample_restaurants").Collection("restaurants")
filter := bson.D{
{"borough", "Queens"},
{"cuisine", "German"},
}
// Deletes all documents that have a "Borough" value of "Queens" and a "Cuisine" value of "German"
results, err := coll.DeleteMany(context.TODO(), filter)
if err != nil {
panic(err)
}
// Prints the number of deleted documents
fmt.Printf("Documents deleted: %d\n", results.DeletedCount)
// When you run this file for the first time, it prints output similar to the following:
// Documents deleted: 6
}
Documents deleted: 6

언급된 작업을 수행하는 방법에 대해 자세히 알아보려면 다음 가이드를 참조하세요:

운전자 컨텍스트를 사용하는 방법에 대해 학습하려면 컨텍스트 패키지를 참조하세요.

힌트 지정에 대한 자세한 내용은 인덱스를 참조하세요.

데이터 정렬에 대해 자세히 학습하려면 golang-collations를 참조하세요.

이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.

돌아가기

업서트

이 페이지의 내용