MongoDB.NET 2.2.4驱动版本对Mongodb3.3数据库中GridFS增删改查_MongoDB

本文实例为大家分享了针对Mongodb3.3数据库中GridFS增删改查,供大家参考,具体内容如下

Program.cs代码如下:

internal class Program
 {
  private static void Main(string[] args)
  {
   GridFSHelper helper = new GridFSHelper("mongodb://localhost", "GridFSDemo", "Pictures"); 

   #region 上传图片 

   //第一种
   //Image image = Image.FromFile("D:\\dog.jpg");
   //byte[] imgdata = ImageHelper.ImageToBytes(image);
   //ObjectId oid = helper.UploadGridFSFromBytes(imgdata); 

   //第二种
   //Image image = Image.FromFile("D:\\man.jpg");
   //Stream imgSteam = ImageHelper.ImageToStream(image);
   //ObjectId oid = helper.UploadGridFSFromStream("man",imgSteam);
   //LogHelper.WriteFile(oid.ToString());
   // Console.Write(oid.ToString()); 

   #endregion 

   #region 下载图片 

   //第一种
   //ObjectId downId = new ObjectId("578e2d17d22aed1850c7855d");
   //byte[] Downdata= helper.DownloadAsByteArray(downId);
   //string name= ImageHelper.CreateImageFromBytes("coolcar",Downdata); 

   //第二种
   // byte[] Downdata = helper.DownloadAsBytesByName("QQQ");
   //string name = ImageHelper.CreateImageFromBytes("dog", Downdata); 

   //第三种
   //byte[] Downdata = helper.DownloadAsBytesByName("QQQ");
   //Image img = ImageHelper.BytesToImage(Downdata);
   //string path = Path.GetFullPath(@"../../DownLoadImg/") + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
   ////使用path获取当前应用程序集的执行目录的上级的上级目录
   //img.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg); 

   #endregion 

   #region 查找图片
   GridFSFileInfo gridFsFileInfo = helper.FindFiles("man");
   Console.WriteLine(gridFsFileInfo.Id);
   #endregion 

   #region 删除图片
   //helper.DroppGridFSBucket();
   #endregion 

   Console.ReadKey();
  }
 }

GridFSHelper.cs的代码如下:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.GridFS; 

namespace MongoDemo
{
 public class GridFSHelper
 {
  private readonly IMongoClient client;
  private readonly IMongoDatabase database;
  private readonly IMongoCollection<BsonDocument> collection;
  private readonly GridFSBucket bucket;
  private GridFSFileInfo fileInfo;
  private ObjectId oid; 

  public GridFSHelper()
   : this(
    ConfigurationManager.AppSettings["mongoQueueUrl"], ConfigurationManager.AppSettings["mongoQueueDb"],
    ConfigurationManager.AppSettings["mongoQueueCollection"])
  {
  } 

  public GridFSHelper(string url, string db, string collectionName)
  {
   if (url == null)
   {
    throw new ArgumentNullException("url");
   }
   else
   {
    client = new MongoClient(url);
   } 

   if (db == null)
   {
    throw new ArgumentNullException("db");
   }
   else
   {
    database = client.GetDatabase(db);
   } 

   if (collectionName == null)
   {
    throw new ArgumentNullException("collectionName");
   }
   else
   {
    collection = database.GetCollection<BsonDocument>(collectionName);
   } 

   //this.collection = new MongoClient(url).GetDatabase(db).GetCollection<BsonDocument>(collectionName); 

   GridFSBucketOptions gfbOptions = new GridFSBucketOptions()
   {
    BucketName = "bird",
    ChunkSizeBytes = 1*1024*1024,
    ReadConcern = null,
    ReadPreference = null,
    WriteConcern = null
   };
   var bucket = new GridFSBucket(database, new GridFSBucketOptions
   {
    BucketName = "videos",
    ChunkSizeBytes = 1048576, // 1MB
    WriteConcern = WriteConcern.WMajority,
    ReadPreference = ReadPreference.Secondary
   });
   this.bucket = new GridFSBucket(database, null);
  } 

  public GridFSHelper(IMongoCollection<BsonDocument> collection)
  {
   if (collection == null)
   {
    throw new ArgumentNullException("collection");
   }
   this.collection = collection;
   this.bucket = new GridFSBucket(collection.Database);
  } 

  public ObjectId UploadGridFSFromBytes(string filename, Byte[] source)
  {
   oid = bucket.UploadFromBytes(filename, source);
   return oid;
  } 

  public ObjectId UploadGridFSFromStream(string filename,Stream source)
  {
   using (source)
   {
    oid = bucket.UploadFromStream(filename, source);
    return oid;
   }
  } 

  public Byte[] DownloadAsByteArray(ObjectId id)
  {
   Byte[] bytes = bucket.DownloadAsBytes(id);
   return bytes;
  } 

  public Stream DownloadToStream(ObjectId id)
  {
   Stream destination = new MemoryStream();
   bucket.DownloadToStream(id, destination);
   return destination;
  } 

  public Byte[] DownloadAsBytesByName(string filename)
  {
   Byte[] bytes = bucket.DownloadAsBytesByName(filename);
   return bytes;
  } 

  public Stream DownloadToStreamByName(string filename)
  {
   Stream destination = new MemoryStream();
   bucket.DownloadToStreamByName(filename, destination);
   return destination;
  } 

  public GridFSFileInfo FindFiles(string filename)
  {
   var filter = Builders<GridFSFileInfo>.Filter.And(
   Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, "man"),
   Builders<GridFSFileInfo>.Filter.Gte(x => x.UploadDateTime, new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc)),
   Builders<GridFSFileInfo>.Filter.Lt(x => x.UploadDateTime, new DateTime(2017, 2, 1, 0, 0, 0, DateTimeKind.Utc)));
   var sort = Builders<GridFSFileInfo>.Sort.Descending(x => x.UploadDateTime);
   var options = new GridFSFindOptions
   {
    Limit = 1,
    Sort = sort
   };
   using (var cursor = bucket.Find(filter, options))
   {
     fileInfo = cursor.ToList().FirstOrDefault();
   }
   return fileInfo;
  } 

  public void DeleteAndRename(ObjectId id)
  {
   bucket.Delete(id);
  } 

  //The “fs.files” collection will be dropped first, followed by the “fs.chunks” collection. This is the fastest way to delete all files stored in a GridFS bucket at once.
  public void DroppGridFSBucket()
  {
   bucket.Drop();
  } 

  public void RenameAsingleFile(ObjectId id,string newFilename)
  {
   bucket.Rename(id, newFilename);
  } 

  public void RenameAllRevisionsOfAfile(string oldFilename,string newFilename)
  {
   var filter = Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, oldFilename);
   var filesCursor = bucket.Find(filter);
   var files = filesCursor.ToList();
   foreach (var file in files)
   {
    bucket.Rename(file.Id, newFilename);
   }
  } 

 }
}

ImageHelper.cs的代码如下:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 

namespace MongoDemo
{
 public static class ImageHelper
 {
  /// <summary>
  /// //将Image转换成流数据,并保存为byte[]
  /// </summary>
  /// <param name="image"></param>
  /// <returns></returns>
  public static byte[] ImageToBytes(Image image)
  {
   ImageFormat format = image.RawFormat;
   using (MemoryStream ms = new MemoryStream())
   {
    if (format.Equals(ImageFormat.Jpeg))
    {
     image.Save(ms, ImageFormat.Jpeg);
    }
    else if (format.Equals(ImageFormat.Png))
    {
     image.Save(ms, ImageFormat.Png);
    }
    else if (format.Equals(ImageFormat.Bmp))
    {
     image.Save(ms, ImageFormat.Bmp);
    }
    else if (format.Equals(ImageFormat.Gif))
    {
     image.Save(ms, ImageFormat.Gif);
    }
    else if (format.Equals(ImageFormat.Icon))
    {
     image.Save(ms, ImageFormat.Icon);
    }
    byte[] buffer = new byte[ms.Length];
    //Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin
    ms.Seek(0, SeekOrigin.Begin);
    ms.Read(buffer, 0, buffer.Length);
    return buffer;
   }
  } 

  public static Stream ImageToStream(Image image)
  {
   ImageFormat format = image.RawFormat;
   MemoryStream ms = new MemoryStream(); 

   if (format.Equals(ImageFormat.Jpeg))
   {
    image.Save(ms, ImageFormat.Jpeg);
   }
   else if (format.Equals(ImageFormat.Png))
   {
    image.Save(ms, ImageFormat.Png);
   }
   else if (format.Equals(ImageFormat.Bmp))
   {
    image.Save(ms, ImageFormat.Bmp);
   }
   else if (format.Equals(ImageFormat.Gif))
   {
    image.Save(ms, ImageFormat.Gif);
   }
   else if (format.Equals(ImageFormat.Icon))
   {
    image.Save(ms, ImageFormat.Icon);
   }
   return ms;
  } 

  //参数是图片的路径
  public static byte[] GetPictureData(string imagePath)
  {
   FileStream fs = new FileStream(imagePath, FileMode.Open);
   byte[] byteData = new byte[fs.Length];
   fs.Read(byteData, 0, byteData.Length);
   fs.Close();
   return byteData;
  } 

  /// <summary>
  /// Convert Byte[] to Image
  /// </summary>
  /// <param name="buffer"></param>
  /// <returns></returns>
  public static Image BytesToImage(byte[] buffer)
  {
   MemoryStream ms = new MemoryStream(buffer);
   Image image = System.Drawing.Image.FromStream(ms);
   return image;
  } 

  /// <summary>
  /// Convert Byte[] to a picture and Store it in file
  /// </summary>
  /// <param name="fileName"></param>
  /// <param name="buffer"></param>
  /// <returns></returns>
  public static string CreateImageFromBytes(string fileName, byte[] buffer)
  {
   string file = fileName;
   Image image = BytesToImage(buffer);
   ImageFormat format = image.RawFormat;
   if (format.Equals(ImageFormat.Jpeg))
   {
    file += ".jpg";
   }
   else if (format.Equals(ImageFormat.Png))
   {
    file += ".png";
   }
   else if (format.Equals(ImageFormat.Bmp))
   {
    file += ".bmp";
   }
   else if (format.Equals(ImageFormat.Gif))
   {
    file += ".gif";
   }
   else if (format.Equals(ImageFormat.Icon))
   {
    file += ".icon";
   }
   System.IO.FileInfo info = new System.IO.FileInfo(Path.GetFullPath(@"DownLoadImg\")); //在当前程序集目录中添加指定目录DownLoadImg
   System.IO.Directory.CreateDirectory(info.FullName);
   File.WriteAllBytes(info+file, buffer);
   return file;
  }
 }
}

LogHelper.cs代码如下:

/// <summary>
 /// 手动记录错误日志,不用Log4Net组件
 /// </summary>
 public class LogHelper
 {
  /// <summary>
  /// 将日志写入指定的文件
  /// </summary>
  /// <param name="Path">文件路径,如果没有该文件,刚创建</param>
  /// <param name="content">日志内容</param>
  public static void WriteFile(string content)
  {
   string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";
   if (!Directory.Exists(Path))
   {
    //若文件目录不存在 则创建
    Directory.CreateDirectory(Path);
   }
   Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";
   if (!File.Exists(Path))
   {
    File.Create(Path).Close();
   }
   StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));
   writer.WriteLine("时间:" + DateTime.Now.ToString());
   writer.WriteLine("日志信息:" + content);
   writer.WriteLine("-----------------------------------------------------------");
   writer.Close();
   writer.Dispose();
  } 

  /// <summary>
  /// 将日志写入指定的文件
  /// </summary>
  /// <param name="Path">文件路径,如果没有该文件,刚创建</param>
  /// <param name="content">日志内容</param>
  public static void WriteFile(int content)
  {
   string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";
   if (!Directory.Exists(Path))
   {
    //若文件目录不存在 则创建
    Directory.CreateDirectory(Path);
   }
   Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";
   if (!File.Exists(Path))
   {
    File.Create(Path).Close();
   }
   StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));
   writer.WriteLine("时间:" + DateTime.Now.ToString());
   writer.WriteLine("日志信息:" + content);
   writer.WriteLine("-----------------------------------------------------------");
   writer.Close();
   writer.Dispose();
  } 

  /// <summary>
  /// 将日志写入指定的文件
  /// </summary>
  /// <param name="erroMsg">错误详细信息</param>
  /// <param name="source">源位置</param>
  /// <param name="fileName">文件名</param>
  public static void WriteFile(string erroMsg, string source, string stackTrace, string fileName)
  {
   string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";
   if (!Directory.Exists(Path))
   {
    //若文件目录不存在 则创建
    Directory.CreateDirectory(Path);
   }
   Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";
   if (!File.Exists(Path))
   {
    File.Create(Path).Close();
   }
   StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));
   writer.WriteLine("时间:" + DateTime.Now.ToString());
   writer.WriteLine("文件:" + fileName);
   writer.WriteLine("源:" + source);
   writer.WriteLine("错误信息:" + erroMsg);
   writer.WriteLine("-----------------------------------------------------------");
   writer.Close();
   writer.Dispose();
  }
 }

结果如下:

Mongodb数据:

查找图片:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索mongodb
, 增删改查
, gridfs
Mongodb3.3
,以便于您获取更多的相关知识。

时间: 2024-09-21 21:52:20

MongoDB.NET 2.2.4驱动版本对Mongodb3.3数据库中GridFS增删改查_MongoDB的相关文章

mongodb+php实现简单的增删改查_MongoDB

windows上安装mongodb的php扩展 下载地址https://s3.amazonaws.com/drivers.mongodb.org/php/index.html 找到对应的php版本的dll文件,下载php_mongo.dll,放到php安装目录下的ext目录中,修改php.ini,添加一项extension=php_mongo.dll,没有找到支持php7的dll 获取MongoClient对象,new出来 获取数据库对象db,通过MongoClient对象的数据库属性,$Mon

Mongodb c#增删改查

写在前面 最近项目需要,就研究了下mongodb,也是为了快速上手,就自己弄了一个简单的例子,这里记录一下. Mongodb 传统的关系数据库一般由数据库(database).表(table).记录(record)三个层次概念组成,MongoDB是由数据库(database).集合(collection).文档对象(document)三个层次组成.MongoDB对于关系型数据库里的表,但是集合中没有列.行和关系概念,这体现了模式自由的特点. 那么在c#如何使用呢?下面看个例子,你会发现上手非常简

Mongodb + PHP 进行增删改查(CRUD)操作教程

用户使用MongoDB开发应用程序使用的是逻辑结构: ● MongoDB的文档,相当于关系数据库中的一行记录 ● 多个文档组成一个集合,相当于关系数据库中的表 ● 多个集合逻辑上组织在一起就是数据库 在安装配置好MongoDB后,我们开始用PHP来实现对数据库的基本操作.所谓基本操作,自然就是我们常说的增删改查(又称CRUD)了. 一.PHP扩展配置 PHP默认是不带mongodb扩展的,在http://www.php.net/manual/en/mongo.installation.php可以

thinkphp3.2.3版本的数据库增删改查实现代码_php实例

框架thinkphp 版本:3.2.3 内容:数据库操作 1. 多表查找一条数据 M('a表')->join("b表 on b表.id=a表.id")->where('条件')->find(); 2.查找一条数据 M('a表')->where('条件')->find(); 3.多表查询所有数据 M('a表')->join("b表 on b表.id=a表.id")->where('条件')->select(); 4.查询

PHP简单操作MongoDB的方法(安装及增删改查)_php技巧

本文实例讲述了PHP简单操作MongoDB的方法.分享给大家供大家参考,具体如下: php操作MongoDB的话首先从网上下载MongoDB的扩展包,https://github.com/mongodb/mongo-php-driver/downloads,选择对应的扩展包. 这是我下的,然后解压,VC6适合apache,VC9适合IIS,ts(thread safe)指PHP以模块形式运行的. 然后把其中的php_mongo.dll放在PHP中的ext文件夹中,然后在PHP.INI里面加入ex

nodejs连接mongodb数据库实现增删改查_node.js

准备 1.通过npm命令安装mongodb 2.安装mongodb数据库,这里不详细介绍了,安装网址:http://www.jb51.net/article/82522.htm CRUD操作 在此之前应对MongoDB数据库有所了解,知道它的一些增删查改命令. 1.增加 var MongoClient = require("mongodb").MongoClient; var DB_URL = "mongodb://localhost:27017/chm"; fun

thinkphp3.2.3版本的数据库增删改查实现代码

框架thinkphp 版本:3.2.3 内容:数据库操作 1. 多表查找一条数据 M('a表')->join("b表 on b表.id=a表.id")->where('条件')->find(); 2.查找一条数据 M('a表')->where('条件')->find(); 3.多表查询所有数据 M('a表')->join("b表 on b表.id=a表.id")->where('条件')->select(); 4.查询

Android编程连接MongoDB及增删改查等基本操作示例

本文实例讲述了Android编程连接MongoDB及增删改查等基本操作.分享给大家供大家参考,具体如下: MongoDB简介 Mongodb,分布式文档存储数据库,由C++语言编写,旨在为WEB应用提供可扩展的高性能数据存储解决方案.MongoDB是一个高性能,开源,无模式的文档型数据库,是当前NoSql数据库中比较热门的一种.它在许多场景下可用于替代传统的关系型数据库或键/值存储方式.Mongo使用C++开发. Mongo安装参考 1)下载安装包文件,解压到某一文件夹下. 官方下载地址:htt

Java操作MongoDB进行增删改查实例教程

现在我们就用Java来操作MongoDB的数据. 一.准备工作 1. 首先,下载mongoDB对Java支持的驱动包 驱动包下载地址:https://github.com/mongodb/mongo-java-driver/downloads mongoDB对Java的相关支持.技术:http://www.mongodb.org/display/DOCS/Java+Language+Center 驱动源码下载:https://download.github.com/mongodb-mongo-j