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

Delete Documents

このガイドでは、削除操作を使用して MongoDB コレクションからドキュメントを削除する方法を学習できます。

このガイドの例では、books コレクション内のドキュメントのモデルとして次の Book 構造体を使用しています。

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)

各ドキュメントには書籍の説明が含まれており、各ドキュメントのtitleauthorlengthフィールドに対応するタイトル、著者、ページ長が含まれています。

Tip

存在しないデータベースとコレクション

書き込み操作を実行するときに必要なデータベースとコレクションが存在しない場合は、サーバーが暗黙的にそれらを作成します。

削除操作を使用して、MongoDB からデータを削除します。 削除操作は、次の方法で構成されています。

  • DeleteOne()は、フィルターに一致する最初のドキュメントを削除します。

  • DeleteMany()は、フィルターに一致するすべてのドキュメントを削除します

Tip

DeleteMany()メソッドの実行時にフィルターに一致するドキュメントが 1 つある場合は、 DeleteOne()メソッドを実行するのと同じです。

DeleteOne()メソッドとDeleteMany()メソッドでは、一致するドキュメントを指定するContextタイプとnon-nilクエリフィルターを渡すことが想定されています。

オプションとして、これらはどちらも削除操作を構成するために使用できるオプションを表す 3 つ目のパラメータとして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プロパティが含まれています。 If there are no matches to your filter, no document gets deleted and DeletedCount is 0.

次の例では、 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

Tip

上記の例でDeleteMany()ではなくDeleteOne()メソッドが使用されている場合、ドライバーは一致した 2 つのドキュメントのうちの最初のドキュメントを削除します。

注意

セットアップ例

この例では、接続 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/ja-jp/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/ja-jp/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

上記の操作の実行方法の詳細については、次のガイドを参照してください。

ドライバーが Context を使用する方法の詳細については、Context パッケージ を参照してください。

ヒントの指定の詳細については、「インデックス 」を参照してください。

照合の詳細については、golang-照合を参照してください。

このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。

戻る

アップサート

項目一覧