NoSQL How to work with MongoDB in .NET

2020.09.30 21:31

졸리운_곰 조회 수:1380

How to work with MongoDB in .NET

Get started with documents and collections in the popular, open source, NoSQL database using C#

MongoDB is a popular, open source, scale-out NoSQL database that provides high throughput for your data-driven applications. Unlike relational databases such as SQL Server, Oracle, and MySQL, which store data in tables according to a rigid schema, MongoDB stores data in documents with flexible schema. There are many such non-relational databases around including CouchDB, RavenDB, and Couchbase. However, I like MongoDB primarily due to its scalability, speed, and dynamic querying capabilities.

MongoDB uses the BSON format under the hood to represent the JSON documents at the heart of the data store. BSON or “Binary JSON” is a lightweight and efficient binary-encoded data serialization format that supports fast data traversal and searches. BSON also allows MongoDB to support data types—namely int, long, date, floating point, and decimal128—not represented in JSON. 

In MongoDB documents are part of collections, in much the same way as a row is part of a table in a relational database. A document is essentially a collection of field and value pairs, which can also be nested. Note that a value in MongoDB can be a document, an array of documents, an array of BSON, or just a BSON type. Let’s look at how we can work with MongoDB using C#. 

Install MongoDB and create a new project

Start by downloading the MongoDB binaries. Unzip the binaries to a folder of your choice in your system and create a separate folder (in my case C:\data\db) for the data. Then, to start MongoDB, navigate to the folder where MongoDB is installed and execute the mongod command in the command prompt window. That should start MongoDB at port 27017 by default.

 
 
 
 
 
 
 
Volume 0%
 

Create a new console application project in Visual Studio and install the MongoDB.Driver package via the NuGet Package Manager Console with the following command.  

PM> Install-Package MongoDB.Driver

This will install the following three NuGet packages at one go.

  • MongoDB.Bson
  • MongoDB.Driver.Core
  • MongoDB.Driver

Connect to your MongoDB instance

To connect to a MongoDB instance at its default port 27017, you can use the default constructor of the MongoClient class as shown below.

var client = new MongoClient();

Now consider the following class. We will use this class to store data in MongoDB.

public class Author
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

Create a database and collection

The following code listing shows how you can create a database and a collection inside it and then insert an object inside the collection.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

static void Main(string[] args)
    {           
        var connectionString ="mongodb://localhost:27017";
        var client = new MongoClient(connectionString);           
        IMongoDatabase db = client.GetDatabase(“IDG”);
        Author author = new Author
        {
            Id = 1,
            FirstName ="Joydip",
            LastName ="Kanjilal"
        };
        var collection = db.GetCollection<Author>(“authors”);
        collection.InsertOne(author);
        Console.Read();
    }

Note that the following namespaces should be included in your program.

using MongoDB.Bson;
using MongoDB.Driver;

Now refer to the Main method in the code listing above. Note that the following statement creates new a database named ”IDG” if none exists by that name.

IMongoDatabase db = client.GetDatabase(“IDG”);

Similarly, the following statement creates a new collection of ”Author” objects if none exists. In either case, the GetCollection method returns a collection instance.

var collection = db.GetCollection<Author>(“authors”);

Add documents to the collection

Next, we create an instance of the Author class and assign values to its FirstName and LastName properties.

Author author = new Author
{
    Id = 1,
    FirstName ="Joydip",
    LastName ="Kanjilal"
};

Use the statement below to insert the instance of the Author class into the collection.

collection.InsertOne(author);

Note that you can insert multiple documents all at the same time using the InsertMany or InsertManyAsync method. The following code listing illustrates how the InsertMany method can be used.

using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;

static void Main(string[] args)
    {           
        var connectionString ="mongodb://localhost:27017";
        var client = new MongoClient(connectionString);           
        IMongoDatabase db = client.GetDatabase(“IDG”);
        var collection = db.GetCollection<BsonDocument>(“IDGAuthors”);
        var author1 = new BsonDocument
        {
            {”id”, 1},
            {”firstname”, Joydip”},
            {”lastname”, Kanjilal”}
        };
        var author2 = new BsonDocument
        {
            {”id”, 2},
            {”firstname”, Steve”},
            {”lastname”, Smith”}
        };
        var author3 = new BsonDocument
        {
            {”id”, 3},
            {”firstname”, Gary”},
            {”lastname”, Stevens”}
        };
        var authors = new List<BsonDocument>();
        authors.Add(author1);
        authors.Add(author2);
        authors.Add(author3);
        collection.InsertMany(authors);
        Console.Read();
    }

The BsonDocument class in the MongoDB.Bson package is used to represent a BSON document. The following code snippet shows how you can display the names of the databases available in the instance of MongoDB running in your system.

var connectionString ="mongodb://localhost:27017";
var client = new MongoClient(connectionString);           
    using (var cursor = client.ListDatabases())
    {
        var databaseDocuments = cursor.ToList();
        foreach (var db in databaseDocuments)
        {
            Console.WriteLine(db[“name”].ToString());
        }
    }

When you execute the above code snippet, you will see the name of the database (i.e., “IDG”) listed in the console window. You can also use the asynchronous method, ListDatabasesAsync, to list the database names, as shown in the code snippet given below.

private static async Task DisplayDatabaseNames()
    {
        var connectionString ="mongodb://localhost:27017";
        var client = new MongoClient(connectionString);
        try
        {
            using (var cursor = await client.ListDatabasesAsync())
            {
                await cursor.ForEachAsync(document => Console.WriteLine(document.ToString()));
            }               
        }
        catch
        {
            //Write your own code here to handle exceptions
        }
    }

MongoDB is a popular NoSQL database that has a flexible data model and scales gracefully. MongoDB provides support for horizontal scalability using a technique known as sharding. I will discuss more advanced concepts in MongoDB in future posts here. Until then, you may want to read up on the MongoDB C# driver in the MongoDB documentation

 

[출처] https://www.infoworld.com/article/3224457/how-to-work-with-mongodb-in-dotnet.html

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 86980
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 79243
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95979
131 [Oracle] sysdate와 systimestamp 정리 및 예제 졸리운_곰 2020.11.12 1928
130 오라클 sysdate 샘플 쿼리 (sysdate - 1) (sysdate - 1/24)의 의미 졸리운_곰 2020.11.12 1414
129 [Oracle] 오라클 EXISTS, NOT EXISTS 사용법 정리 (IN, JOIN 비교) file 졸리운_곰 2020.11.10 2433
128 [오라클, oracle] ORA-00926:missing VALUES keyword 오류 졸리운_곰 2020.11.07 1807
127 [oracle] [오라클] SUBSTR, SUBSTRB 함수 사용방법 (문자열, 자르기, 바이트, Left) file 졸리운_곰 2020.11.07 1526
126 [Oracle] ORA-00917: 누락된 콤마 졸리운_곰 2020.11.07 1641
125 [oracle] 오라클 MOD 함수(나머지 구하기 함수, 초를 분으로 변경) 졸리운_곰 2020.11.07 1170
124 [몽고디비 mongodb] 몽고디비에서 벌크 오퍼려이션과 배열 삽입의 차이점은 what is the difference between bulk insert and array insert in Mongo db operations 졸리운_곰 2020.10.09 1258
123 [oracle] 성능 향상을 위한 다중 로우 처리 졸리운_곰 2020.10.09 1235
122 BULK SQL 사용예 졸리운_곰 2020.10.09 1561
121 Oracle :: MERGE INTO 졸리운_곰 2020.09.10 1565
120 오라클 MERGE INTO - 한번에 INSERT, UPDATE 하기 졸리운_곰 2020.09.10 1197
119 Oracle Merge 명령어 사용 file 졸리운_곰 2020.09.10 1324
118 [오라클] ORA-01476 제수가 0 입니다 졸리운_곰 2020.07.22 2083
117 다중 with문 사용 - ORACLE SQL | [PL]SQL 졸리운_곰 2020.06.28 1640
116 여러 개의 INSERT문을 한 번에 처리 졸리운_곰 2020.06.28 1239
115 [Oracle] 오라클 WITH절 사용법 & 예제 (임시 테이블 만들기) file 졸리운_곰 2020.06.28 1342
114 [oracle] WITH 구문 file 졸리운_곰 2020.06.28 1396
113 [Oracle] WITH 구문 예제 file 졸리운_곰 2020.06.28 3266
112 [oracle]오라클 group by, rollup file 졸리운_곰 2020.06.28 1174
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED