예상 완료 시간: 5분
Atlas 클러스터에 연결한 후에는 클러스터와 상호 작용할 수 있습니다. 이 튜토리얼에서는 mongosh
, Atlas UI, MongoDB Compass 또는 지원되는 MongoDB 드라이버를 사용하여 클러스터에 데이터를 삽입하고 새 데이터를 읽습니다.
➤ 언어 선택 드롭다운 메뉴를 사용해 이 튜토리얼의 언어를 설정합니다.
필요한 액세스 권한
클러스터와 상호 작용하려면 데이터베이스 사용자여야 합니다.
전제 조건
시작하기 전에 원하는 연결 방법을 구성해야 합니다. 자세히 알아보려면 클러스터에 연결을 참조하세요.
데이터 삽입 및 보기
Atlas는 클러스터의 데이터와 상호 작용할 수 있는 GUI를 제공합니다.
AtlasGo Atlas 에서 프로젝트 의 Data Explorer 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 내비게이션 바의 Projects 메뉴에서 프로젝트를 선택합니다.
사이드바에서 Database 제목 아래의 Data Explorer를 클릭합니다.
데이터 탐색기 가 표시됩니다.
참고
Clusters 페이지로 이동하여 Shortcuts 제목 아래의 Data Explorer 을 클릭할 수도 있습니다.
collection에 문서를 삽입합니다.
Collection이 선택되지 않은 경우
people
collection을 선택합니다.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에 다른 값이 표시될 수 있습니다.
팁
자세히 알아보려면 문서 생성, 보기, 업데이트 및 삭제하기를 참조하세요.
데이터베이스에 문서를 삽입합니다.
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
(이)라는 새 컬렉션을 생성하고 해당 컬렉션에 문서 한 개를 삽입합니다.
문서를 봅니다.
클러스터에 방금 삽입한 데이터를 보려면 다음 명령을 실행하여 people
컬렉션에서 name.last
값이 Turing
인 문서를 검색합니다.
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에 다른 값이 표시될 수 있습니다.
팁
MongoDB에서 데이터를 쿼리하는 방법에 대해 자세히 알아보려면 문서 쿼리를 참조하세요.
MongoDB Compass에서 cluster에 연결합니다.
MongoDB Compass 열고 클러스터 에 연결합니다. 연결에 대한 자세한 지침은 Compass 를 통해 클러스터에 연결하기를 참조하세요.
collection에 문서를 삽입합니다.
왼쪽 탐색에서
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에 다른 값이 표시될 수 있습니다.
팁
자세한 내용은 Compass 문서를 참조하세요.
다음은 샘플 애플리케이션입니다.
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
gettingStarted
데이터베이스에서people
컬렉션에 문서를 삽입합니다people
collection에서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에 다른 값이 표시될 수 있습니다.
팁
C#으로 데이터를 쿼리하는 방법에 대해 자세히 알아보려면 C# 문서를 참조하세요.
다음은 샘플 애플리케이션입니다.
Atlas 클러스터에 대한 연결을 설정합니다.
gettingStarted
데이터베이스에서people
컬렉션에 문서를 삽입합니다people
collection에서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에 다른 값이 표시될 수 있습니다.
팁
Go로 데이터를 쿼리하는 방법에 대해 자세히 알아보려면 Go 문서를 참조하세요.
다음은 샘플 애플리케이션입니다.
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
gettingStarted
데이터베이스에서people
컬렉션에 문서를 삽입합니다people
collection에서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에 다른 값이 표시될 수 있습니다.
팁
Java로 데이터를 쿼리하는 방법에 대해 자세히 알아보려면 Java 설명서를 참조하세요.
다음은 샘플 애플리케이션입니다.
Atlas 클러스터에 대한 연결을 설정합니다.
gettingStarted
데이터베이스에서people
컬렉션에 문서를 삽입합니다people
collection에서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에 다른 값이 표시될 수 있습니다.
팁
Node.js로 데이터를 쿼리하는 방법에 대해 자세히 알아보려면 Node.js 설명서를 참조하세요.
다음은 샘플 애플리케이션입니다.
Atlas 클러스터에 대한 연결을 설정합니다.
gettingStarted
데이터베이스에서people
컬렉션에 문서를 삽입합니다people
collection에서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에 다른 값이 표시될 수 있습니다.
팁
PyMongo로 데이터를 쿼리하는 방법에 대해 자세히 알아보려면 PyMongo 문서를 참조하세요.
다음 단계
클러스터를 계속 성장시키는 경우 더 많은 사용자와 연산을 지원할 수 있록 클러스터를 확장하는 것이 좋습니다.
샘플 데이터 세트를 로드하여 MongoDB에서 데이터를 빠르게 실험하고 Atlas UI 및 MongoDB Charts 와 같은 도구를 사용할 수 있습니다. 자세히 알아보려면 Atlas에 데이터 로드하기를 참조하세요.
합성 데이터를 생성할 수도 있습니다. 자세히 알아보려면 합성 데이터 생성을 참조하세요.