적용 대상:
Mongodb
Important
기존 MongoDB 애플리케이션을 마이그레이션하거나 MQL(MongoDB 쿼리 언어) 기능을 사용하시겠습니까? Azure DocumentDB를 고려합니다.
여러 지역에서 99.999% 가용성 서비스 수준 계약, 즉각적인 자동 크기 조정 및 자동 장애 조치(failover)가 있는 대규모 시나리오에 대한 데이터베이스 솔루션을 찾고 있나요? NoSQL용 Azure Cosmos DB를 고려하십시오.
네이티브 MongoDB 클라이언트 드라이버를 사용하여 Azure Cosmos DB에 저장된 MongoDB 컬렉션을 관리합니다.
비고
예제 코드 조각은 GitHub에서 .NET 프로젝트로 사용할 수 있습니다.
API for MongoDB 참조 설명서 | MongoDB 패키지(NuGet)
컬렉션 이름 지정
Azure Cosmos DB에서 컬렉션은 관계형 데이터베이스의 테이블과 유사합니다. 컬렉션을 만들 때 컬렉션 이름은 컬렉션 리소스 및 모든 자식 문서에 액세스하는 데 사용되는 URI의 세그먼트를 형성합니다.
컬렉션 인스턴스 가져오기
컬렉션 클래스의 인스턴스를 사용하여 서버의 컬렉션에 액세스합니다.
다음 코드 조각은 이미 클라이언트 연결을 만들었다고 가정합니다.
컬렉션 만들기
컬렉션을 만들려면 컬렉션에 문서를 삽입합니다.
- MongoClient.Database.Collection
- MongoClient.Database.Collection.InsertOne
- MongoClient.Database.Collection.InsertMany
// insert one document
var product = new BsonDocument
{
{ "name", "Sand Surfboard" },
{ "category", "gear-surf-surfboards" },
{ "count", 1 }
};
client.GetDatabase("adventureworks").GetCollection<BsonDocument>("products").InsertOne(product);
// insert many documents
var products = new List<BsonDocument>()
{
new BsonDocument
{
{ "name", "Sand Surfboard" },
{ "category", "gear-surf-surfboards" },
{ "count", 1 }
},
new BsonDocument
{
{ "name", "Ocean Surfboard" },
{ "category", "gear-surf-surfboards" },
{ "count", 5 }
}
};
client.GetDatabase("adventureworks").GetCollection<BsonDocument>("products").InsertMany(products);
컬렉션 삭제
영구적으로 제거하려면 데이터베이스에서 컬렉션을 삭제합니다. 그러나 컬렉션에 액세스하는 다음 삽입 또는 업데이트 작업은 해당 이름으로 새 컬렉션을 만듭니다.
client.GetDatabase("adventureworks").DropCollection("products");
컬렉션 인덱스 가져오기
인덱스는 MongoDB 쿼리 엔진에서 데이터베이스 쿼리의 성능을 향상시키는 데 사용됩니다.
var indexes = client.GetDatabase("adventureworks").GetCollection<BsonDocument>("products").Indexes;
var count = 0;
using (var cursor = await indexes.ListAsync())
{
do
{
if (cursor.Current != null)
{
foreach (var index in cursor.Current)
{
Console.WriteLine(cursor.Current);
count++;
}
}
}
while (await cursor.MoveNextAsync());
}