MongoDB からのデータの削除
Overview
このガイドでは、MongoDB からデータを削除します。
所要時間: 10 分
必要なもの
stringMongoDB配置への 接続 。
MongoDB へのデータの挿入 ガイドから挿入されたデータ。
手順
MongoDB インスタンスに接続します。
コレクションのドキュメントに似たクラスを作成します。
次のクラスは、ドキュメントに含まれるすべてのフィールド名とタイプをリストします。
1 // class that maps to the fields of a document in the sample_guides.comets collection
2 class Comet {
3 public ObjectId Id { get; set; }
4 public string Name { get; set; }
5 public string OfficialName { get; set; }
6 public double OrbitalPeriod { get; set; }
7 public double Radius { get; set; }
8 public double Mass { get; set; }
9 }
クラスをドキュメント フィールドに自動マッピングします。
C# では、フィールドを慣例的に大文字のクラス プロパティにマッピングします。 ただし、キャメルケース フィールドを含むデータは削除する必要があります。 ドライバがフィールドを大文字からキャメルケースに自動変換するようにするには、 ConventionPack
を作成し、 CamelCase
の命名規則を登録します。
1 // instruct the driver to camelCase the fields in MongoDB 2 var pack = new ConventionPack { new CamelCaseElementNameConvention() }; 3 ConventionRegistry.Register("elementNameConvention", pack, x => true);
接続コードを確認します。
Tip
以下は、MongoDB に接続するために最低限必要なコードの概要です。 次の数ステップで、データを削除するための追加を行います。
6 行目で、URI 文字列を独自の Atlas 接続文字列に置き換えます。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Conventions; 3 using MongoDB.Driver; 4 5 // Replace the uri string with your MongoDB deployment's connection string. 6 var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 7 8 // instruct the driver to read the fields in camelCase 9 var pack = new ConventionPack { new CamelCaseElementNameConvention() }; 10 ConventionRegistry.Register("elementNameConvention", pack, x => true); 11 12 var client = new MongoClient(uri); 13 14 // database and collection code goes here 15 // delete code goes here 16 // amount deleted code goes here 17 18 // class that represents the fields of a document in the 19 // sample_guides.comets collection 20 class Comet { 21 public ObjectId Id { get; set; } 22 public string Name { get; set; } 23 public string OfficialName { get; set; } 24 public double OrbitalPeriod { get; set; } 25 public double Radius { get; set; } 26 public double Mass { get; set; } 27 }
Tip
以下は、MongoDB に接続するために最低限必要なコードの概要です。 次の数ステップで、データを削除するための追加を行います。
15 行目の URI 文字列を独自の Atlas 接続文字列に置き換えます。
1 package main 2 3 import ( 4 "context" 5 6 "go.mongodb.org/mongo-driver/v2/mongo" 7 "go.mongodb.org/mongo-driver/v2/mongo/options" 8 ) 9 10 func main() { 11 uri := "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority" 12 13 client, err := mongo.Connect(options.Client().ApplyURI(uri)) 14 if err != nil { 15 panic(err) 16 } 17 18 defer func() { 19 if err = client.Disconnect(context.TODO()); err != nil { 20 panic(err) 21 } 22 }() 23 24 // database and collection code goes here 25 // delete code goes here 26 // amount deleted code goes here 27 }
Tip
以下は、MongoDB に接続するために最低限必要なコードの概要です。 次の数ステップで、データを削除するための追加を行います。
13 行目の URI 文字列を独自の Atlas 接続文字列に置き換えます。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import com.mongodb.client.result.DeleteResult; 6 import com.mongodb.client.model.Filters; 7 8 import org.bson.Document; 9 import org.bson.conversions.Bson; 10 11 public class CrudDelete { 12 public static void main(String[] args) { 13 String uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 14 15 try (MongoClient mongoClient = MongoClients.create(uri)) { 16 // database and collection code goes here 17 // insert code goes here 18 // amount deleted code goes here 19 } 20 } 21 }
Tip
以下は、MongoDB に接続するために最低限必要なコードの概要です。 次の数ステップで、データを削除するための追加を行います。
5 行目で、URI 文字列を独自の Atlas 接続文字列に置き換えます。
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = 5 "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 6 7 const client = new MongoClient(uri); 8 9 async function run() { 10 try { 11 await client.connect(); 12 // database and collection code goes here 13 // delete code goes here 14 // amount deleted code goes here 15 } finally { 16 // Ensures that the client will close when you finish/error 17 await client.close(); 18 } 19 } 20 run().catch(console.dir);
Tip
以下は、MongoDB に接続するために最低限必要なコードの概要です。 次の数ステップで、データを削除するための追加を行います。
4 行目で、URI 文字列を独自の Atlas 接続文字列に置き換えます。
1 from pymongo import MongoClient 2 3 # Replace the uri string with your MongoDB deployment's connection string. 4 uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority" 5 6 client = MongoClient(uri) 7 8 # database and collection code goes here 9 # delete code goes here 10 # amount deleted code goes here 11 12 # Close the connection to MongoDB when you're done. 13 client.close()
Tip
mongodb+srv
srv
オプションを選択した状態で、PyMongo をインストールしておきます。
python3 -m pip install "pymongo[srv]"
データベースとコレクションを取得します。
クエリするデータベースとコレクションに切り替えます。 この場合は、 sample_guides
データベースとcomets
コレクションを使用します。
// database and collection code goes here
var db = client.GetDatabase("sample_guides");
var coll = db.GetCollection<Comet>("comets");
1 // database and colletion code goes here 2 db := client.Database("sample_guides") 3 coll := db.Collection("comets")
1 // database and collection code goes here 2 MongoDatabase db = mongoClient.getDatabase("sample_guides"); 3 MongoCollection<Document> coll = db.getCollection("comets");
// database and collection code goes here const db = client.db("sample_guides"); const coll = db.collection("comets");
# database and collection code goes here db = client.sample_guides coll = db.comets
comets
コレクション内の特定のドキュメントを削除します。
次の例では、クエリフィルターを使用して、 orbitalPeriod
が 5 より大きく 85 より小さいドキュメントを削除する方法を示しています。
// delete code goes here var result = coll.DeleteMany(x => x.OrbitalPeriod > 5 && x.OrbitalPeriod < 85);
1 // delete code goes here 2 filter := bson.D{ 3 {"$and", 4 bson.A{ 5 bson.D{{"orbitalPeriod", bson.D{{"$gt", 5}}}}, 6 bson.D{{"orbitalPeriod", bson.D{{"$lt", 85}}}}, 7 }, 8 }, 9 }
MongoDB Java Sync ドライバーには、クエリ(およびその他の操作)の作成プロセスを簡素化する Builder が含まれます。ここでは、Filters.and
、Filters.lt
、Filters.gt
ビルダを使用してクエリドキュメントを構築します。
1 // delete code goes here 2 Bson filter = Filters.and(Filters.gt("orbitalPeriod", 5), Filters.lt("orbitalPeriod", 85)); 3 DeleteResult result = coll.deleteMany(filter);
// delete code goes here const doc = { orbitalPeriod: { $gt: 5, $lt: 85 } }; const result = await coll.deleteMany(doc);
# delete code goes here doc = { "orbitalPeriod": { "$gt": 5, "$lt": 85 } } result = coll.delete_many(doc)
結果を表示します。
result
には削除操作に関するいくつかの情報が含まれています。 削除されたドキュメントを確認するには、ドライバーが削除したドキュメントの量を出力します。
// amount deleted code goes here Console.WriteLine($"Number of documents deleted: {result.DeletedCount}");
1 // amount deleted code goes here 2 fmt.Printf("Number of documents deleted: %d", result.DeletedCount)
1 // amount deleted code goes here 2 System.out.println("Number of documents deleted: " +result.getDeletedCount());
// amount deleted code goes here console.log("Number of documents deleted: " + result.deletedCount);
# amount deleted code goes here print("Number of documents deleted: ", result.deleted_count)
結果を確認します。
完全なコードとサンプル出力は次のとおりです。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Conventions; 3 using MongoDB.Driver; 4 5 // Replace the uri string with your MongoDB deployment's connection string. 6 var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 7 8 // instruct the driver to read the fields in camelCase 9 var pack = new ConventionPack { new CamelCaseElementNameConvention() }; 10 ConventionRegistry.Register("elementNameConvention", pack, x => true); 11 12 var client = new MongoClient(uri); 13 14 // database and collection code goes here 15 var db = client.GetDatabase("sample_guides"); 16 var coll = db.GetCollection<Comet>("comets"); 17 18 // delete code goes here 19 var result = coll.DeleteMany(x => x.OrbitalPeriod > 5 && x.OrbitalPeriod < 85); 20 21 // amount deleted code goes here 22 Console.WriteLine($"Number of documents deleted: {result.DeletedCount}"); 23 24 // class that maps to the fields of a document in the sample_guides.comets collection 25 class Comet 26 { 27 public ObjectId Id { get; set; } 28 public string Name { get; set; } 29 public string OfficialName { get; set; } 30 public double OrbitalPeriod { get; set; } 31 public double Radius { get; set; } 32 public double Mass { get; set; } 33 }
Number of documents deleted: 2
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 7 "go.mongodb.org/mongo-driver/v2/bson" 8 "go.mongodb.org/mongo-driver/v2/mongo" 9 "go.mongodb.org/mongo-driver/v2/mongo/options" 10 ) 11 12 func main() { 13 uri := "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority" 14 15 client, err := mongo.Connect(options.Client().ApplyURI(uri)) 16 if err != nil { 17 panic(err) 18 } 19 20 defer func() { 21 if err = client.Disconnect(context.TODO()); err != nil { 22 panic(err) 23 } 24 }() 25 26 // database and colletion code goes here 27 db := client.Database("sample_guides") 28 coll := db.Collection("comets") 29 30 // delete code goes here 31 filter := bson.D{ 32 {"$and", 33 bson.A{ 34 bson.D{{"orbitalPeriod", bson.D{{"$gt", 5}}}}, 35 bson.D{{"orbitalPeriod", bson.D{{"$lt", 85}}}}, 36 }, 37 }, 38 } 39 40 result, err := coll.DeleteMany(context.TODO(), filter) 41 if err != nil { 42 panic(err) 43 } 44 45 // amount deleted code goes here 46 fmt.Printf("Number of documents deleted: %d", result.DeletedCount) 47 }
Number of documents deleted: 2
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import com.mongodb.client.result.DeleteResult; 6 import com.mongodb.client.model.Filters; 7 8 import org.bson.Document; 9 import org.bson.conversions.Bson; 10 11 public class CrudDelete { 12 public static void main(String[] args) { 13 String uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 14 15 try (MongoClient mongoClient = MongoClients.create(uri)) { 16 // database and collection code goes here 17 MongoDatabase db = mongoClient.getDatabase("sample_guides"); 18 MongoCollection<Document> coll = db.getCollection("comets"); 19 20 // delete code goes here 21 Bson filter = Filters.and(Filters.gt("orbitalPeriod", 5), Filters.lt("orbitalPeriod", 85)); 22 DeleteResult result = coll.deleteMany(filter); 23 24 // amount deleted code goes here 25 System.out.println("Number of documents deleted: " +result.getDeletedCount()); 26 } 27 } 28 }
Number of documents deleted: 2
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = 5 "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 6 7 const client = new MongoClient(uri); 8 9 async function run() { 10 try { 11 await client.connect(); 12 // database and collection code goes here 13 const db = client.db("sample_guides"); 14 const coll = db.collection("comets"); 15 16 // delete code goes here 17 const doc = { 18 orbitalPeriod: { 19 $gt: 5, 20 $lt: 85 21 } 22 }; 23 24 const result = await coll.deleteMany(doc); 25 26 // amount deleted code goes here 27 console.log("Number of documents deleted: " + result.deletedCount); 28 29 } finally { 30 // Ensures that the client will close when you finish/error 31 await client.close(); 32 } 33 } 34 run().catch(console.dir);
Number of documents deleted: 2
1 from pymongo import MongoClient 2 3 # Replace the uri string with your MongoDB deployment's connection string. 4 uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority" 5 6 client = MongoClient(uri) 7 8 # database and collection code goes here 9 db = client.sample_guides 10 coll = db.comets 11 12 # delete code goes here 13 doc = { 14 "orbitalPeriod": { 15 "$gt": 5, 16 "$lt": 85 17 } 18 } 19 result = coll.delete_many(doc) 20 21 # amount deleted code goes here 22 print("Number of documents deleted: ", result.deleted_count) 23 24 # Close the connection to MongoDB when you're done. 25 client.close()
Number of documents deleted: 2
概要
このガイドを読み終えたら、MongoDB からデータを削除したことになります。
これで、MongoDB の CRUD 操作の紹介は完了します。
その他の参照
ここで紹介した概念に関する詳しい情報については、次のリソースを参照してください。
The MongoDB C#ドライバー のドキュメンテーション
The MongoDB Go ドライバーのドキュメンテーション
The MongoDB Java (Sync) ドライバーのドキュメント
The MongoDB Node.js ドライバーのドキュメンテーション
PyMongo のドキュメンテーション