使用Mongo驱动程序将文件上传到Mongo Atlas

时间:2017-07-04 02:35:53

标签: c# mongodb mongodb-replica-set

我正在尝试使用C#Mongo Driver将文件上传到Mongo Atlas。但我不明白如何连接类MongoServerSettings。我试过这个:

private static MongoServerSettings GetMongoConfig()
{
    var credential = MongoCredential.CreateCredential("admin", "XXXX", "XXXX");

    MongoServerAddress[] servers = new MongoServerAddress[3];
    servers[0] = new MongoServerAddress("cluster0-shard-00-00-XXXXX.mongodb.net", 27017);
    servers[1] = new MongoServerAddress("cluster0-shard-00-01-XXXX.mongodb.net", 27017);
    servers[2] = new MongoServerAddress("cluster0-shard-00-02-XXXX.mongodb.net", 27017);

    var ServerSetting = new MongoServerSettings {
        ConnectionMode = ConnectionMode.ReplicaSet,
        UseSsl = true,                
        Servers = servers,
        ReplicaSetName = "Cluster0-shard-0",
        Credentials = new[]{ credential },
    };

    return ServerSetting;
}

public static void SavePDFInvoice(HttpPostedFileBase file,string fileID, string userID, string userOwner)
{
    var Server = new MongoServer(GetMongoConfig());

    var grid = new MongoGridFS(Server, PDFDatabase, new MongoGridFSSettings());
    grid.Upload(file.InputStream, fileID, new MongoGridFSCreateOptions
    {
        Id = fileID,
        Metadata = new BsonDocument {
            { "userID", userID},
            { "userOwner", userOwner},
        } 
    });
}

但是,不起作用。

我可以连接mongoclient类,但我不知道如何使用MongoGridFS类。

1 个答案:

答案 0 :(得分:1)

您可以查看此链接,了解如何使用C#

连接到mongodb Atlas

https://docs.atlas.mongodb.com/driver-connection/#c-net-driver-example

从链接:

要连接到Atlas M0(免费套餐)群集,您必须使用支持MongoDB 3.4的C#/ .Net驱动程序版本。

var client = new MongoClient("your clister url");
var database = client.GetDatabase("test");