1. 程式人生 > >NoSQL資料庫—MongoDB入門使用和c#客戶端的訪問

NoSQL資料庫—MongoDB入門使用和c#客戶端的訪問

{
            
//連結字串
string connectionString ="mongodb://localhost";

            
//資料庫名
string databaseName ="myDatabase";

            
//定義Mongo服務
            MongoServer server = MongoServer.Create(connectionString);

            
//獲取databaseName對應的資料庫,不存在則自動建立
            MongoDatabase mongoDatabase = server.GetDatabase(databaseName) 
as MongoDatabase;

            MongoCollection
<BsonDocument> books = mongoDatabase.GetCollection<BsonDocument>("books");


            
//連結資料庫
            server.Connect();
            
try
            
{
                BsonDocument book 
=new BsonDocument 
                
{
                    
"author
""Ernest Hemingway" }
,
                    
"title""For Whom the Bell Tolls" }
                }
;
                books.Insert(book);

                var query 
=new QueryDocument("author""Ernest Hemingway");
                
foreach (BsonDocument bookItem in books.Find(query))
                
{
                    Console.WriteLine(book[
"author"]);
                }

            }

            
finally
            
{
                
//關閉連結
                server.Disconnect();
            }

            Console.Read();
        }