关于C#中MongoDB基础操作的小例子

ET框架最后的DB模块,尝试了一些MongoDB在C#中的基本操作,便于理解ET的相关方法。需要说明的一点,对象保存为文档时,private成员不会保存,public和protected成员会被保存,可以添加[BsonIgnore]标签忽略掉。
官网教程:https://docs.mongodb.com/drivers/csharp/

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

                        database.GetCollection<Entity2>(typeof(Entity2).Name).ReplaceOne(d => d.Id == 2, entity2, new ReplaceOptions { IsUpsert = true });
		}

		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()
			{
			}
		}
	}
}
posted @ 2021-11-20 21:18  qianxun0975  阅读(626)  评论(1编辑  收藏  举报