.net 操作MongoDB 基础

1. 下载驱动,最好使用 NuGet 下载,直接搜索MongoDB;

.net 操作MongoDB 基础

2. 引用相关驱动

.net 操作MongoDB 基础

3. 部分测试代码,主要是针对MongoDB的GridFS 文件存储来用

 using Mongo.Model;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.GridFS;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web; namespace Mongo.Helper
{
public static class MongoDBHelper
{ public static MongoClient client = new MongoClient("mongodb://localhost:27017");
public static IMongoDatabase db = client.GetDatabase("dzdaTest");//获取需要操作数据库
public static void Add(Model.UserInfo user)
{
var collects = db.GetCollection<Model.UserInfo>("user");//获取需要操作的集合
collects.InsertOne(user);
} public static List<UserInfo> FindAll()
{
List<UserInfo> lis = new List<UserInfo>();
var collects = db.GetCollection<UserInfo>("user");
var filter = new BsonDocument();
using(var cursor = collects.Find(filter).ToCursor())//查询结果转化为类似游标的类型
{
while (cursor.MoveNext())
{
foreach (UserInfo item in cursor.Current)
{
lis.Add(item);
}
}
}
return lis;
} /// <summary>
/// 上传图片
/// </summary>
/// <param name="name"></param>
/// <param name="source"></param>
/// <returns></returns>
public static ObjectId UploadImg(string name, byte[] source)
{
var bucket = new GridFSBucket(db);//初始化GridFS
return bucket.UploadFromBytes(name, source);
}
/// <summary>
/// 上传图片
/// </summary>
/// <param name="name"></param>
/// <param name="source"></param>
/// <returns></returns>
public static ObjectId UploadImg(string name, Stream source)
{
var bucket = new GridFSBucket(db);
return bucket.UploadFromStream(name, source);
} public async static Task<ObjectId> UploadImgAsync(string name, Stream source)
{
var bucket = new GridFSBucket(db);
return await bucket.UploadFromStreamAsync(name, source);
}
/// <summary>
/// 查询图片
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static Stream FindImg(string id)
{
var bucket = new GridFSBucket(db);
ObjectId objId= new ObjectId(id);//通过ObjectId查询图片
return bucket.OpenDownloadStream(objId);
} /// <summary>
/// 查询图片
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static byte[] FindImgWithByte(string id)
{
var bucket = new GridFSBucket(db);
ObjectId objId = new ObjectId(id);
return bucket.DownloadAsBytes(objId);
}
}
}

    

上一篇:火狐mozilla官方ftp站点获取旧版本火狐的下载地址


下一篇:Linux中查看系统版本的方法