1. 程式人生 > 其它 >關於C#中MongoDB基礎操作的小例子

關於C#中MongoDB基礎操作的小例子

ET框架最後的DB模組,嘗試了一些MongoDB在C#中的基本操作,便於理解ET的相關方法。

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

namespace TestLambda
{
	class Program
	{
		static void Main()
		{
			MongoClient client = new MongoClient("mongodb://127.0.0.1:27017");
			IMongoDatabase database = client.GetDatabase("mymongo");

			var collection = database.GetCollection<BsonDocument>("mymongo3");  //獲取集合例項,如果不存在則自動建立,BsonDocument需要using MongoDB.Bson;
			var document = new BsonDocument	//建立文件例項
			{
				{ "name", "MongoDB" },
				{ "type", "Database" },
				{ "count", 1 },
				{ "info", new BsonDocument
					{
						{ "x", 203 },
						{ "y", 102 }
					}}
			};

			//InsertOne插入單個文件
			//mongosh中使用db.mymongo3.find()可以查詢到這條記錄
			collection.InsertOne(document);

			//InsertMany插入多個文件
			//Linq語句:Enumerable.Range生成指定範圍內的整數的序列;Enumerable.Select遍歷序列投影到新表單
			var documents = Enumerable.Range(0, 10).Select(i => new BsonDocument("i", i));
			collection.InsertMany(documents);

			long count = collection.CountDocuments(new BsonDocument()); //統計文件數量
			Console.WriteLine(count);

			//Find查詢結果返回首條資料
			BsonDocument documentResult = collection.Find(new BsonDocument()).FirstOrDefault();
			Console.WriteLine(documentResult.ToString());

			//Find查詢結果轉換為集合遍歷輸出
			List<BsonDocument> documentsResult = collection.Find(new BsonDocument()).ToList();
			for (int i = 0; i < documentsResult.Count; i++)
			{
				Console.WriteLine(documentsResult[i]);
			}

			//Find查詢結果轉換為遊標遍歷輸出,配合ToEnumerable列舉器
			IAsyncCursor<BsonDocument> cursor = collection.Find(new BsonDocument()).ToCursor();
			foreach (var doc in cursor.ToEnumerable())
			{
				Console.WriteLine(doc);
			}

			//建立一個過濾器傳遞給Find方法進行查詢
			var filter = Builders<BsonDocument>.Filter.Eq("count", 1);
			var documentFilter = collection.Find(filter).First();
			Console.WriteLine(documentFilter);

			//==================================================

			//看看直接儲存物件例項是什麼內容
			var collectionClass1 = database.GetCollection<Entity1>("MongoClass1");

			Entity1 entity1 = new Entity1(1, "Entity1");
			collectionClass1.InsertOne(entity1);
			#region Find輸出
			//[ { _id: 1, Name: 'Entity1' } ]
			#endregion

			//加個巢狀試試
			var collectionClass2 = database.GetCollection<Entity2>("MongoClass2");

			Component component = new Component(10, "Component");
			Entity2 entity2 = new Entity2(2, "Entity2", component);
			collectionClass2.InsertOne(entity2);
			#region Find輸出
			//[
			//	{
			//		_id: 2,
			//		Name: 'Entity2',
			//		component: { _id: 10, Name: 'Component' }
			//	}
			//]
			#endregion
		}

		public class Entity1
		{
			public int Id { get; set; }
			public string Name { get; set; }

			public Entity1(int id, string name)
			{
				Id = id;
				Name = name;
			}
		}

		public class Entity2
		{
			public int Id { get; set; }
			public string Name { get; set; }
			public Component component { get; set; }

			public Entity2(int id, string name, Component component)
			{
				Id = id;
				Name = name;
				this.component = component;
			}
		}

		public class Component
		{
			public int Id { get; set; }
			public string Name { get; set; }

			public Component(int id, string name)
			{
				Id = id;
				Name = name;
			}

			public Component()
			{
			}
		}
	}
}