如何在c#中从mongodb集合生成json文件?

时间:2014-04-19 10:47:01

标签: c# json mongodb

好的,所以我是mongodb数据库的新手。我创建了一个小型测试类,用'Country'对象填充数据库。现在,我想将数据库中的数据提取到一个json文件..我在互联网上看到了所有地方,在堆栈上,但是找不到答案,请帮忙......

public class Country
{
    public string Name { get; set; }
    public string Language { get; set; }
    public string Capital_City { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        try
        {
            var connectionString = "mongodb://localhost";
            var client = new MongoClient(connectionString);
            var server = client.GetServer();
            var database = server.GetDatabase("Countries");
            var collection = database.GetCollection<Country>("Countries");

            BsonClassMap.RegisterClassMap<Country>(x =>
                {
                    x.MapProperty(c => c.Name);
                    x.MapProperty(c => c.Language);
                    x.MapProperty(c => c.Capital_City);
                });
            hardCodedInfo(collection);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    static void hardCodedInfo(MongoCollection collection)
    {
        var tmp1 = new Country() { Capital_City = "Belgrade", Name = "Serbia", Language = "Serbian" };
        collection.Insert(tmp1);
        var tmp2 = new Country() { Capital_City = "Vienna", Name = "Austria", Language = "German" };
        collection.Insert(tmp2);
        var tmp3 = new Country() { Capital_City = "Beijing", Name = "China", Language = "Mandarin" };
        collection.Insert(tmp3);
        var tmp4 = new Country() { Capital_City = "Moscow", Name = "Russia", Language = "Russian" };
        collection.Insert(tmp4);
        var tmp5 = new Country() { Capital_City = "Tokio", Name = "Japan", Language = "Japanese" };
        collection.Insert(tmp5);
        var tmp6 = new Country() { Capital_City = "Brasilia", Name = "Brasil", Language = "Portugese" };
        collection.Insert(tmp6);
        var tmp7 = new Country() { Capital_City = "Paris", Name = "France", Language = "French" };
        collection.Insert(tmp7);
        var tmp8 = new Country() { Capital_City = "Antananarivo", Name = "Madagascar", Language = "Malagasy" };
        collection.Insert(tmp8);
        var tmp9 = new Country() { Capital_City = "Andorra la Vella", Name = "Andorra", Language = "Catalan" };
        collection.Insert(tmp9);
        var tmp10 = new Country() { Capital_City = "Ulan Bator", Name = "Mongolia", Language = "Mongolian" };
        collection.Insert(tmp10);
    }
}

0 个答案:

没有答案