链接数据库
public static MongoDatabase GetDatabase()
{
string connectionString = "localhost:27017";
string dbName = "fileTest";
var server = MongoServer.Create(connectionString);
return server.GetDatabase(dbName);
}
获取GridFS表
public static MongoGridFS GetMongoGridFS(string collection)
{
MongoDatabase DB = GetDatabase();
MongoGridFSSettings fsSetting = new MongoGridFSSettings() { Root = collection };
MongoGridFS fs = new MongoGridFS(DB, fsSetting);
return fs;
}
添加数据(上传文件)
public void upload()
{
MongoGridFS fs = GetMongoGridFS("File"); // 传入表名字符串
string fullpath = "C:/Users/Administrator/Desktop/image.png";
string filename = "image.png";
using (FileStream sr = new FileStream(fullpath, FileMode.Open))
{
MongoGridFSCreateOptions option = new MongoGridFSCreateOptions();
BsonDocument doc = new BsonDocument();
string[] pathArr = FullPath.Split('\\');
doc.Add("operator", "Administrator");
doc.Add("time", "20180504");
option.Metadata = doc; // 添加metadata数据
fs.Upload(sr, filename, option);
}
}
删除数据
public void delete()
{
MongoGridFS fs = GetMongoGridFS("File"); // 传入表名字符串
string name = "Administrator";
var query = new QueryDocument("metadata.operator", name);
fs.Delete(query);
//fs.DeleteById(BsonObjectId.Parse(id)); // id为string类型
}
查询数据
MongoGridFS fs = GetMongoGridFS("File"); // 传入表名字符串
List<MongoGridFSFileInfo> pList = fs.FindAll().SetSortOrder("filename").ToList();
List<MongoGridFSFileInfo> pList = fs.FindAll().OrderBy(x => x.metadata["time"]).ToList();
List<MongoGridFSFileInfo> pList = fs.FindAll().GroupBy(x => x.Metadata["Administrator"]).ToList(); // 分组查询
List<MongoGridFSFileInfo> pList = fs.FindAll().GroupBy(x => x.Metadata["Administrator"])
.Select(x => new{
Administrator = x.First().Metadata["Administrator"],
count = x.Count()
}).ToList(); // 分组查询返回部分结果
其他查询可查看https://blog.csdn.net/w174504744/article/details/45936109
下载文件
public void download()
{
MongoGridFS fs = GetMongoGridFS("File"); // 传入表名字符串
fs.Download(Response.OutputStream, "image.png");
//fs.Download("D:/", "image.png"); // 下载到指定目录
}