MongoDB C# Driver 使用示例 (2.2)

  1. class Program  
  2.   {  
  3.       const string CollectionName = "video";  
  4.       static void Main(string[] args)  
  5.       {  
  6.           // remove the demo collection then recreate later  
  7.           db.GetCollection<Video>(CollectionName).Database.DropCollection(CollectionName);  
  8.   
  9.   
  10.           var videos = new List<Video>  
  11.           {  
  12.               new Video { Title="The Perfect Developer",   
  13.                           Category="SciFi", Minutes=118 },  
  14.               new Video { Title="Lost In Frankfurt am Main",   
  15.                           Category="Horror", Minutes=122 },   
  16.               new Video { Title="The Infinite Standup",   
  17.                           Category="Horror", Minutes=341 }   
  18.           };  
  19.   
  20.   
  21.           Console.WriteLine("Insert Videos ...");  
  22.   
  23.   
  24.           db.GetCollection<Video>(CollectionName).InsertMany(videos);  
  25.   
  26.   
  27.           Console.WriteLine("[After insert] All Videos : ");  
  28.           var all = db.GetCollection<Video>(CollectionName).Find(x=>x.Title != string.Empty).ToList();  
  29.           foreach (var v in all)  
  30.           {  
  31.               Console.WriteLine(v);  
  32.           }  
  33.   
  34.   
  35.           Console.WriteLine("Group By...");  
  36.   
  37.   
  38.           var groupby = db.GetCollection<Video>(CollectionName).Aggregate()  
  39.                   .Group(x => x.Category, g => new {Name = g.Key, Count = g.Count(), TotalMinutes = g.Sum(x => x.Minutes)})  
  40.                   .ToList();  
  41.           foreach (var v in groupby)  
  42.           {  
  43.               Console.WriteLine(v.Name + "," + v.Count + "," + v.TotalMinutes);  
  44.           }  
  45.   
  46.   
  47.   
  48.   
  49.           Console.WriteLine("Updating One [Title = The Perfect Developer]...");  
  50.   
  51.   
  52.           // updating title with "The perfect developer" video's 'title' and 'minute'  
  53.           db.GetCollection<Video>(CollectionName).FindOneAndUpdate(x=>x.Title == "The Perfect Developer",  
  54.                   Builders<Video>.Update.Set(x=> x.Title , "A Perfect Developer [updated]")  
  55.                                         .AddToSet(x => x.Comments, "good video!")  
  56.                                         .AddToSet(x => x.Comments, "not bad"));  
  57.   
  58.   
  59.           Console.WriteLine("[After Updating One] All Videos : ");  
  60.           all = db.GetCollection<Video>(CollectionName).Find(x => x.Title != string.Empty).ToList();  
  61.           foreach (var v in all)  
  62.           {  
  63.               Console.WriteLine(v);  
  64.           }  
  65.   
  66.   
  67.           Console.WriteLine("Deleting One... [Minutes = 122]");  
  68.           db.GetCollection<Video>(CollectionName).DeleteOne(x => x.Minutes == 122);  
  69.           Console.WriteLine("[After Deleting One] All Videos : ");  
  70.           all = db.GetCollection<Video>(CollectionName).Find(x => x.Title != string.Empty).ToList();  
  71.           foreach (var v in all)  
  72.           {  
  73.               Console.WriteLine(v);  
  74.           }  
  75.   
  76.   
  77.           Console.Read();  
  78.       }  
  79.   
  80.   
  81.       private static IMongoDatabase db  
  82.       {  
  83.           get  
  84.           {  
  85.               var url = new MongoUrl(ConfigurationSettings.AppSettings["mongoUrl"]);  
  86.               var client = new MongoClient(url);  
  87.               return client.GetDatabase(url.DatabaseName);  
  88.           }  
  89.       }  
  90.   }  
  91.   
  92.   
  93.   [BsonIgnoreExtraElements]  
  94.   public class Video  
  95.   {  
  96.       public Video()  
  97.       {  
  98.           Comments = new List<string>();  
  99.       }  
  100.   
  101.   
  102.       [BsonId]  
  103.       [BsonRepresentation(BsonType.ObjectId)]  
  104.       public string Id { getset; }  
  105.   
  106.   
  107.       public string Title { getset; }  
  108.       public string Category { getset; }  
  109.       public int Minutes { getset; }  
  110.   
  111.   
  112.       public IList<string> Comments { getset; }  
  113.   
  114.   
  115.       public override string ToString()  
  116.       {  
  117.           return string.Format("{0} - {1} - {2}", Title, Category, Minutes);  
  118.       }  
  119.   }  


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MongoDB.Driver;
using MongoDB.Bson;


namespace MongoDBTest
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Mongo();
        }

        public void Mongo()
        {
            //建立连接
            var client = new MongoClient();
            //建立数据库
            var database = client.GetDatabase("TestDb");
            //建立collection
            var collection = database.GetCollection<BsonDocument>("foo");

            var document = new BsonDocument
            {
                {"name","MongoDB"},
                {"type","Database"},
                {"count",1},
                {"info",new BsonDocument{{"x",203},{"y",102}}}
            };
            //插入数据
            collection.InsertOne(document);

            var count = collection.Count(document);
            Console.WriteLine(count);

            //查询数据
            var document1 = collection.Find(document);
            Console.WriteLine(document1.ToString());

            //更新数据
            var filter = Builders<BsonDocument>.Filter.Eq("name", "MongoDB");
            var update = Builders<BsonDocument>.Update.Set("name", "Ghazi");

            collection.UpdateMany(filter, update);

            //删除数据
            var filter1 = Builders<BsonDocument>.Filter.Eq("count", 101);

            collection.DeleteMany(filter1);

            BsonDocument document2 = new BsonDocument();
            document2.Add("name", "MongoDB");
            document2.Add("type", "Database");
            document2.Add("count", "1");

            collection.InsertOne(document2);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#使用MongoDB示例代码有几个部分。首先,你需要引用MongoDB的命名空间,例如"using MongoDB.Driver;"。然后,你需要建立一个MongoDB的客户端和数据库连接。你可以使用连接字符串来指定连接参数,如服务器地址和数据库名称。连接字符串可以通过配置文件读取,也可以直接在代码中指定。接下来,你需要指定要操作的集合名称,获取该集合的引用。你可以使用查询条件来过滤集合中的文档,并使用Find方法获取满足条件的文档列表。最后,你可以遍历文档列表,并输出文档中的字段值。在示例代码中,输出的姓名和电话字段分别通过p["name"]和p["phone"]来获取。示例代码中还展示了一种插入文档的方法,使用InsertOneAsync方法将一个文档插入到集合中。关于连接方式的不同,你可以选择使用连接字符串来建立连接,也可以直接指定服务器地址和数据库名称。但无论使用哪种方式,你都需要确保连接参数的正确性和有效性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [1.C#操作MongoDB](https://blog.csdn.net/qq_34035956/article/details/125716599)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *3* [在C#使用MongoDB](https://blog.csdn.net/u011301348/article/details/89330590)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值