推定所要時間: 5 分
MongoDB Atlas クラスターに を接続したら、クラスターと交流できます。このチュートリアルでは、mongosh 、 Atlas UI 、 MongoDB Compass 、またはサポートされている MongoDB ドライバー を使用して、クラスターにデータを挿入し、新しいデータを読み取ります。
➤ このチュートリアルの方法を設定するには、[言語の選択] ドロップダウン メニューを使用します。
必要なアクセス権
クラスターと対話するには、データベース ユーザーである必要があります。
前提条件
開始する前に、優先する接続方法を設定する必要があります。詳しくは、 MongoDB Search Community.を参照してください。
データの挿入と表示
Atlas は、クラスター内のデータとやりとりするための GUI を提供します。
AtlasData Explorer で、プロジェクトの ページに移動します。
まだ表示されていない場合は、プロジェクトを含む組織をナビゲーション バーの Organizations メニューで選択します。
まだ表示されていない場合は、ナビゲーション バーの Projects メニューからプロジェクトを選択します。
サイドバーで、 Database見出しの下のData Explorerをクリックします。
Data Explorerが表示されます。
データベースに peopleコレクションを作成します。gettingStarted
+ Create Databaseボタンをクリックします。
Database Name に
gettingStartedと入力します。Collection Name に
peopleと入力します。Create をクリックして、データベースとその最初のコレクションを作成します。
コレクションにドキュメントを挿入します。
peopleコレクションが未選択の場合、選択します。[Insert Document] をクリックします。
デフォルトのドキュメントを置換するには、JSON ビュー ({}) をクリックします。
次のコードを貼り付けます。
{ "name": { "first": "Alan", "last": "Turing" }, "birth": { "$date": "1912-06-23" }, "death": { "$date": "1954-06-07" }, "contribs": [ "Turing machine", "Turing test", "Turingery" ], "views": 1250000 } [Insert] をクリックしてドキュメントを追加します。
[Insert Document] をクリックします。
デフォルトのドキュメントを置換するには、JSON ビュー ({}) をクリックします。
次のコードを貼り付けます。
{ "name": { "first": "Grace", "last": "Hopper" }, "birth": { "$date": "1906-12-09" }, "death": { "$date": "1992-01-01" }, "contribs": [ "Mark I", "UNIVAC", "COBOL" ], "views": 3860000 } [Insert] をクリックしてドキュメントを追加します。
ドキュメントを見る
[Apply] をクリックしてクエリを実行し、挿入したドキュメントを表示します。クエリ結果に次のドキュメントが表示されます。
_id: ObjectId('64d52c3c3db2144fc00791b9'}, name: Object first: "Alan" last: "Turing" birth: 1912-06-23T06:00:00.000+00:00 death: 1954-06-07T05:00:00.000+00:00 contribs: Array 0: "Turing machine" 1: "Turing test" 2: "Turingery" views: 1250000
注意
ObjectId はシステムによって生成された値であるため、異なる値が表示されることがあります。
Tip
詳しくは、「ドキュメントの作成、表示、アップデート、削除」を参照してください。
データベースにドキュメントを挿入します。
mongosh で次のコマンドを実行して、新しいデータベースにドキュメントを挿入します。
db.people.insertMany([ { name: { first: 'Alan', last: 'Turing' }, birth: new Date('Jun 23, 1912'), death: new Date('Jun 07, 1954'), contribs: [ 'Turing machine', 'Turing test', 'Turingery' ], views : Long(1250000) }, { name: { first: 'Grace', last: 'Hopper' }, birth: new Date('Dec 9, 1906'), death: new Date('Jan 1, 1992'), contribs: [ 'Mark I', 'UNIVAC', 'COBOL' ], views : Long(3860000) }] );
{ acknowledged: true, insertedIds: { '0': ObjectId('65c28946edcfbff3c7ce90c4'), '1': ObjectId('65c28946edcfbff3c7ce90c5') } }
注意
ObjectId はシステムによって生成された値であるため、異なる値が表示されることがあります。
このコマンドで、gettingStarted データベースに people という新しい コレクションを作成し、そのコレクションにドキュメントを 1 つ挿入します。
ドキュメントを見る
クラスターに挿入したばかりのドキュメントを表示するには、次のコマンドを実行して people コレクションから Turing に name.last 値を持つドキュメントを検索します。
db.people.find({ "name.last": "Turing" })
{ _id: ObjectId("65c28946edcfbff3c7ce90c4"), name: { first: 'Alan', last: 'Turing' }, birth: ISODate("1912-06-23T04:00:00Z"), death: ISODate("1954-06-07T04:00:00Z"), contribs: [ 'Turing machine', 'Turing test', 'Turingery' ], views: Long("1250000") }
注意
ObjectId はシステムによって生成された値であるため、異なる値が表示されることがあります。
Tip
MongoDB でデータをクエリする方法について詳しくは「ドキュメントのクエリ」を参照してください。
MongoDB Compass のクラスターに接続します。
MongoDB Compassを開き、クラスターに接続します。接続の詳細な手順については、Compass 経由でクラスターに接続する を参照してください。
データベースに peopleコレクションを作成します。gettingStarted
左側のナビゲーションの Databases セクションで、[] をクリックします。
Database Name に
gettingStartedと入力します。Collection Name に
peopleと入力します。Create Database をクリックして、データベースとその最初のコレクションを作成します。
コレクションにドキュメントを挿入します。
左側のナビゲーションで、
gettingStartedデータベースをクリックします。peopleコレクションを選択します。コレクションの Documents タブで、[Add Data] をクリックします。
Insert Document をクリックして、次のコードを貼り付けます。
{ "name": { "first": "Alan", "last": "Turing" }, "birth": { "$date": "1912-06-23" }, "death": { "$date": "1954-06-07" }, "contribs": [ "Turing machine", "Turing test", "Turingery" ], "views": 1250000 } [Insert] をクリックしてドキュメントを追加します。
コレクションの Documents タブで、[Add Data] をクリックします。
Insert Document をクリックして、次のコードを貼り付けます。
{ "name": { "first": "Grace", "last": "Hopper" }, "birth": { "$date": "1906-12-09" }, "death": { "$date": "1992-01-01" }, "contribs": [ "Mark I", "UNIVAC", "COBOL" ], "views": 3860000 } [Insert] をクリックしてドキュメントを追加します。
ドキュメントを見る
[Find] をクリックしてクエリを実行し、挿入したドキュメントを表示します。クエリ結果に次のドキュメントが表示されます。
_id: ObjectId('65c28c938dfecbc5fb1bd220'}, name: Object first: "Alan" last: "Turing" birth: 1912-06-23T06:00:00.000+00:00 death: 1954-06-07T05:00:00.000+00:00 contribs: Array 0: "Turing machine" 1: "Turing test" 2: "Turingery" views: 1250000
注意
ObjectId はシステムによって生成された値であるため、異なる値が表示されることがあります。
Tip
詳しくは、Compass のドキュメントを参照してください。
サンプル アプリケーションは次の操作を行います。
mongodbパッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
gettingStartedデータベース内のpeopleというコレクションにドキュメントを挿入します。peopleコレクション内でname.lastの値がTuringであるドキュメントを検索し、そのドキュメントを返します。
ドライバーと依存関係がインストールされた NET/C# プロジェクトで、次のコードを Program.cs ファイルにコピーします。
注意
プレースホルダーを Atlas の接続文字列に置き換えます。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 6 public class InsertData 7 { 8 // Replace the following with your Atlas connection string 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // Connect to your Atlas cluster 14 var client = new MongoClient(MongoConnectionString); 15 16 // Reference the database and collection to use 17 var database = client.GetDatabase("gettingStarted"); 18 var peopleCollection = database.GetCollection<Person>("people"); 19 20 // Create new documents 21 var newPerson = new List<Person>() { 22 new Person { 23 Name = new Name { First = "Alan", Last = "Turing" }, 24 Birth = new DateTime(1912, 5, 23), // May 23, 1912 25 Death = new DateTime(1954, 5, 7), // May 7, 1954 26 Contribs = new string[] {"Turing machine", "Turing test", "Turingery"}, 27 Views = 1250000 28 },new Person { 29 Name = new Name { First = "Grace", Last = "Hopper" }, 30 Birth = new DateTime(1906, 12, 9), // Dec 9, 1906 31 Death = new DateTime(1992, 1, 1), // Jan 1, 1992 32 Contribs = new string[] {"Mark I", "UNIVAC", "COBOL"}, 33 Views = 3860000 34 } 35 }; 36 37 // Insert the documents into the specified collection 38 peopleCollection.InsertMany(newPerson); 39 40 // Find the document 41 var filter = Builders<Person>.Filter 42 .Eq(person => person.Name.Last, "Turing"); 43 44 var document = peopleCollection.Find(filter).FirstOrDefault(); 45 46 // Print the result 47 Console.WriteLine($"Document found:\n{document.ToBsonDocument()}"); 48 } 49 } 50 51 public class Person 52 { 53 public ObjectId Id { get; set; } 54 public Name Name { get; set; } 55 public DateTime Birth { get; set; } 56 public DateTime Death { get; set; } 57 public string[] Contribs { get; set; } 58 public int Views { get; set; } 59 } 60 public class Name 61 { 62 public string First { get; set; } 63 public string Last { get; set; } 64 }
サンプル アプリケーションを実行するには、次のコマンドを使用します。
dotnet run Program.cs
Document found: { "_id" : ObjectId("65c28fcf87156efe024c4558"), "Name" : { "First" : "Alan", "Last" : "Turing" }, "Birth" : ISODate("1912-05-23T06:00:00Z"), "Death" : ISODate("1954-05-07T05:00:00Z"), "Contribs" : ["Turing machine", "Turing test", "Turingery"], "Views" : 1250000 }
注意
ObjectId はシステムによって生成された値であるため、異なる値が表示されることがあります。
Tip
C# でデータをクエリする方法について詳しくは、C# のドキュメントを参照してください。
サンプル アプリケーションは次の操作を行います。
Atlas クラスターへの接続を確立します。
gettingStartedデータベース内のpeopleというコレクションにドキュメントを挿入します。peopleコレクション内でname.lastの値がTuringであるドキュメントを検索し、そのドキュメントを返します。
ドライバーと依存関係がインストールされた Go プロジェクトで、insert-data.go というファイルを作成し、次のコードをファイルにコピーします。
注意
プレースホルダーを Atlas の接続文字列に置き換えます。
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/v2/bson" 9 "go.mongodb.org/mongo-driver/v2/mongo" 10 "go.mongodb.org/mongo-driver/v2/mongo/options" 11 ) 12 13 // Defines structure of documents in the people collection 14 type Person struct { 15 Name Name 16 Birth time.Time 17 Death time.Time 18 Contribs []string 19 Views int 20 } 21 22 type Name struct { 23 First string 24 Last string 25 } 26 27 func main() { 28 29 // Replace the following with your Atlas connection string 30 uri := "<connection-string>" 31 32 // Connects to your Atlas cluster 33 client, err := mongo.Connect(options.Client().ApplyURI(uri)) 34 if err != nil { 35 panic(err) 36 } 37 defer client.Disconnect(context.TODO()) 38 39 // References the database and collection to use 40 collection := client.Database("gettingStarted").Collection("people") 41 42 // Creates new documents 43 newPeople := []interface{}{ 44 Person{ 45 Name: Name{First: "Alan", Last: "Turing"}, 46 Birth: time.Date(1912, 5, 23, 0, 0, 0, 0, time.UTC), // May 23, 1912 47 Death: time.Date(1954, 5, 7, 0, 0, 0, 0, time.UTC), // May 7, 1954 48 Contribs: []string{"Turing machine", "Turing test", "Turingery"}, 49 Views: 1250000, 50 }, 51 Person{ 52 Name: Name{First: "Grace", Last: "Hopper"}, 53 Birth: time.Date(1906, 12, 9, 0, 0, 0, 0, time.UTC), // Dec 9, 1906 54 Death: time.Date(1992, 1, 1, 0, 0, 0, 0, time.UTC), // Jan 1, 1992 55 Contribs: []string{"Mark I", "UNIVAC", "COBOL"}, 56 Views: 3860000, 57 }, 58 } 59 60 // Inserts the document into the specified collection 61 collection.InsertMany(context.TODO(), newPeople) 62 63 // Finds the document 64 collection = client.Database("gettingStarted").Collection("people") 65 filter := bson.D{{Key: "name.last", Value: "Turing"}} 66 67 var result Person 68 err = collection.FindOne(context.TODO(), filter).Decode(&result) 69 if err != nil { 70 panic(err) 71 } 72 73 // Prints results 74 fmt.Printf("Document Found:\n%+v\n", result) 75 }
サンプル アプリケーションを実行するには、次のコマンドを使用します。
go run insert-data.go
Document Found: {Name:{First:Alan Last:Turing} Birth:1912-05-23 00:00:00 +0000 UTC Death:1954-05-07 00:00:00 +0000 UTC Contribs:[Turing machine Turing test Turingery] Views:1250000}
注意
ObjectId はシステムによって生成された値であるため、異なる値が表示されることがあります。
Tip
Go を使用してデータをクエリする方法について詳しくは、Go のドキュメントを参照してください。
サンプル アプリケーションは次の操作を行います。
mongodbパッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
gettingStartedデータベース内のpeopleというコレクションにドキュメントを挿入します。peopleコレクション内でname.lastの値がTuringであるドキュメントを検索し、そのドキュメントを返します。
ドライバーと依存関係がインストールされた Java プロジェクトで、InsertData.java というファイルを作成し、作成したファイルに次のコードをコピーします。
注意
プレースホルダーを Atlas の接続文字列に置き換えます。
1 import static com.mongodb.client.model.Filters.eq; 2 import com.mongodb.client.MongoClient; 3 import com.mongodb.client.MongoClients; 4 import com.mongodb.client.MongoCollection; 5 import com.mongodb.client.MongoDatabase; 6 import com.mongodb.client.result.InsertManyResult; 7 import com.mongodb.MongoException; 8 9 import java.util.Arrays; 10 import java.util.List; 11 import java.util.Date; 12 import java.time.Instant; 13 import org.bson.types.ObjectId; 14 import org.bson.Document; 15 16 public class InsertData { 17 public static void main(String[] args) { 18 // Replace the placeholder with your Atlas connection string 19 String uri = "<connection-string>"; 20 21 // Connect to your Atlas Cluster and insert a document 22 try (MongoClient mongoClient = MongoClients.create(uri)) { 23 // Reference the database and collection to use 24 MongoDatabase database = mongoClient.getDatabase("gettingStarted"); 25 MongoCollection<Document> collection = database.getCollection("people"); 26 27 // Create two documents 28 List<Document> peopleList = Arrays.asList( 29 new Document().append("name", new Document().append("first", "Alan").append("last", "Turing")) 30 .append("birth", Date.from(Instant.parse("1912-05-23T00:00:00.000+00:00"))) 31 .append("death", Date.from(Instant.parse("1954-05-07T00:00:00.000+00:00"))) 32 .append("contribs", Arrays.asList("Turing machine", "Turing test", "Turingery")) 33 .append("views", 1250000), 34 new Document().append("name", new Document().append("first", "Grace").append("last", "Hopper")) 35 .append("birth", Date.from(Instant.parse("1906-12-09T00:00:00.000+00:00"))) 36 .append("death", Date.from(Instant.parse("1992-01-01T00:00:00.000+00:00"))) 37 .append("contribs", Arrays.asList("Mark I", "UNIVAC", "COBOL")) 38 .append("views", 3860000) 39 ); 40 41 try { 42 // Insert the documents into the specified collection 43 InsertManyResult result = collection.insertMany(peopleList); 44 } catch (MongoException me) { 45 System.err.println("Unable to insert due to an error: " + me); 46 } 47 // Find the document 48 Document document = collection.find(eq("name.last", "Turing")) 49 .first(); 50 51 // Print results 52 if (document == null) { 53 System.out.println("No results found."); 54 } else { 55 System.out.println("Document found:"); 56 System.out.println(document.toJson()); 57 } 58 } 59 } 60 }
次に、SortDateForSpeed.java ファイルをコンパイルして実行します。
javac InsertData.java java InsertData
Document found: {"_id": {"$oid": "64d52c3c3db2144fc00791b9"}, "name": {"first": "Alan", "last": "Turing"}, "birth": {"$date": {"$numberLong": "-1815328800000"}}, "death": {"$date": {"$numberLong": "-491338800000"}}, "contribs": ["Turing machine", "Turing test", "Turingery"], "views": 1250000}
注意
ObjectId はシステムによって生成された値であるため、異なる値が表示されることがあります。
Tip
Java でデータをクエリする方法について詳しくは、Java のドキュメントを参照してください。
サンプル アプリケーションは次の操作を行います。
Atlas クラスターへの接続を確立します。
gettingStartedデータベース内のpeopleというコレクションにドキュメントを挿入します。peopleコレクション内でname.lastの値がTuringであるドキュメントを検索し、そのドキュメントを返します。
insert-data.js という名前でファイルを作成し、そのファイルに次のコードをコピーします。
注意
プレースホルダーを Atlas の接続文字列に置き換えます。
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the following with your Atlas connection string 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async function run() { 10 try { 11 // Connect to the Atlas cluster 12 await client.connect(); 13 14 // Get the database and collection on which to run the operation 15 const db = client.db("gettingStarted"); 16 const col = db.collection("people"); 17 18 // Create new documents 19 const peopleDocuments = [ 20 { 21 "name": { "first": "Alan", "last": "Turing" }, 22 "birth": new Date(1912, 5, 23), // May 23, 1912 23 "death": new Date(1954, 5, 7), // May 7, 1954 24 "contribs": [ "Turing machine", "Turing test", "Turingery" ], 25 "views": 1250000 26 }, 27 { 28 "name": { "first": "Grace", "last": "Hopper" }, 29 "birth": new Date(1906, 12, 9), // Dec 9, 1906 30 "death": new Date(1992, 1, 1), // Jan 1, 1992 31 "contribs": [ "Mark I", "UNIVAC", "COBOL" ], 32 "views": 3860000 33 } 34 ] 35 36 // Insert the documents into the specified collection 37 const p = await col.insertMany(peopleDocuments); 38 39 // Find the document 40 const filter = { "name.last": "Turing" }; 41 const document = await col.findOne(filter); 42 43 // Print results 44 console.log("Document found:\n" + JSON.stringify(document)); 45 46 } catch (err) { 47 console.log(err.stack); 48 } 49 50 finally { 51 await client.close(); 52 } 53 } 54 55 run().catch(console.dir);
サンプル アプリケーションを実行するには、次のコマンドを使用します。
node insert-data.js
Document found: {"_id":"65c296ae128a3f34abda47e0","name":{"first":"Alan","last":"Turing"},"birth":"1912-06-23T06:00:00.000Z","death":"1954-06-07T05:00:00.000Z","contribs":["Turing machine","Turing test","Turingery"],"views":1250000}
注意
ObjectId はシステムによって生成された値であるため、異なる値が表示されることがあります。
Tip
Node.js でデータをクエリする方法について詳しくは、Node.js のドキュメントを参照してください。
サンプル アプリケーションは次の操作を行います。
Atlas クラスターへの接続を確立します。
gettingStartedデータベース内のpeopleというコレクションにドキュメントを挿入します。peopleコレクション内でname.lastの値がTuringであるドキュメントを検索し、そのドキュメントを返します。
ドライバーと依存関係がインストールされた Python プロジェクトで、insert-data.py というファイルを作成し、次のコードをファイルにコピーします。
注意
プレースホルダーを Atlas の接続文字列に置き換えます。
1 import pymongo 2 import datetime 3 4 # connect to your Atlas cluster 5 client = pymongo.MongoClient('<connection-string>') 6 7 # get the database and collection on which to run the operation 8 collection = client['gettingStarted']['people'] 9 10 # create new documents 11 peopleDocuments = [ 12 { 13 "name": { "first": "Alan", "last": "Turing" }, 14 "birth": datetime.datetime(1912, 6, 23), 15 "death": datetime.datetime(1954, 6, 7), 16 "contribs": [ "Turing machine", "Turing test", "Turingery" ], 17 "views": 1250000 18 }, 19 { 20 "name": { "first": "Grace", "last": "Hopper" }, 21 "birth": datetime.datetime(1906, 12, 9), 22 "death": datetime.datetime(1992, 1, 1), 23 "contribs": [ "Mark I", "UNIVAC", "COBOL" ], 24 "views": 3860000 25 } 26 ] 27 28 # insert documents 29 collection.insert_many(peopleDocuments) 30 31 # find documents 32 result = collection.find_one({ "name.last": "Turing" }) 33 34 # print results 35 print("Document found:\n", result)
サンプル アプリケーションを実行するには、次のコマンドを使用します。
1 python insert-data.py
Document found: { '_id': ObjectId('65c2a8188388383b00a85b1f'), 'name': { 'first': 'Alan', 'last': 'Turing' }, 'birth': datetime.datetime(1912, 6, 23, 0, 0), 'death': datetime.datetime(1954, 6, 7, 0, 0), 'contribs': [ 'Turing machine', 'Turing test', 'Turingery' ], 'views': 1250000 }
注意
ObjectId はシステムによって生成された値であるため、異なる値が表示されることがあります。
Tip
PyMongo を使用したデータのクエリの詳細については、PyMongo のドキュメントを参照してください。
次のステップ
クラスターを拡張し続ける場合は、より多くのユーザーと操作をサポートするために クラスターのスケーリング を検討してください。
サンプル データセットをロードすると、MongoDB のデータの実験をすぐに開始でき、Atlas UI や MongoDB Charts などのツールを使用できます。詳しくは、「Atlas にデータをロードする」を参照してください。
合成データを生成することもできます。詳しくは、「合成データの生成」を参照してください。