C# MongoDb 数据转化为Json

				var str = "mongodb://127.0.0.1:27017";
                var client = new MongoDB.Driver.MongoClient(str);
                var db = client.GetDatabase("Test2018");
                var t = db.ListCollectionsAsync();
                t.Wait();
                var tCursor = t.Result.ToListAsync();
                tCursor.Wait();
                var vtName = tCursor.Result;
                var names = vtName.Select(b => b["name"].ToString()).ToArray();
                for(var i = 0; i<names.Length; i++)
                {
                    var name = names[i];
                    if (name == "system.indexes")
                        continue;
                    var col = db.GetCollection<BsonDocument>(name);              
                    var c = col.Find(new BsonDocument());
                    var datas = c.ToList();                    
                    var jsons = datas.Select(t => t.ToJson()).ToArray();                  
                    var content = string.Join("\r\n", jsons);//这里就是Json文档                             
                }

需要MongoDb的官方Driver
Namespace:
using MongoDB.Bson;
using MongoDB.Driver;

posted on 2024-07-08 02:52  norsd  阅读(2)  评论(0编辑  收藏  举报  来源

导航