Store images in MongoDB using DotNet Core 3.0
MongoDB is a document database designed for ease of development and scaling. The data is stored and queried as JSON documents. To follow this tutorial, you need to have the following installed and working on your computer:
- MongoDB database
- MongoDB Compass
- Visual Studio 2019 or Visual Studio Code (with OmniSharp extension to work with DotNet Core projects
- DotNet Core 3.0 or above
There is a GridFS option too that allows you to store files outside the database but according to MongoDB official documentation it is optimized for files larger than 16MB. For files smaller than 16MB, it is recommended to store them inside the MongoDB documents.
For our tutorial we will use a simple object and store the images as binary data type. MongoDB has a builtin data type called "BinData" which allows to store binary data as a byte array.
Create a new Dotnet Core Console App project using Visual Studio 2019 or Visual Studio Code.
Create a new class as shown below.
public class Question
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Category { get; set; }
public string Type { get; set; }
public string QuestionHeading { get; set; }
public byte[] ContentImage { get; set; }
public decimal Score { get; set; }
}
Notice that we have a property named ContentImage as the byte[] array. We will store an image inside this array.
Now create a service class that will open a MongoDB connection using the dotnet driver for MongoDB and store the document with the image data inside it.
public class QuestionService
{
private readonly IMongoCollection<Question> _questions;
public QuestionService(IDatabaseSettings settings)
{
var client = new MongoClient("<YOUR CONNECTION STRING>");
var database = client.GetDatabase("<YOUR DATABASE NAME>");
_questions = database.GetCollection<Question>("Questions");
}
public Question Get(string id)
{
var result = _questions.Find(
q => q.Id == id).FirstOrDefault();
return result;
}
public Question Create(Question question)
{
_questions.InsertOne(question);
return question;
}
}
The code above for inserting and retrieving data from MongoDB is pretty standard. Make sure you create your MongoDB database and a collection named Questions within it.
Next, in your Main method of your Program class, write the following code:
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var service = new QuestionService();
// CONVERT JPG TO A BYTE ARRAY
byte[] binaryContent = File.ReadAllBytes("image.jpg");
var question = new Question
{
Category = "Children's Quizzes",
Type = "Puzzles",
QuestionHeading = "Find the cat in the below image",
ContentImage = binaryContent, // Store the byte array in ContentImage property
Score = 10
};
service.Create(question);
}
Run MongoDB Compass and connect to your MongoDB Atlas instance. Read more about creating an Atlas instance on AWS here.
Ensure that you have your database created and also created a collection named Questions inside it.
Run the code in Visual Studio. Once the code runs, go back to your MongoDB Compass and refress your Questions collection. You should be able to see a new document created inside the collection.
Notice the data inside field ContentImage. It is of type Binary or BinData as it is called in MongoDB vocabulary.
It is so easy to store images inside MongoDB using Dotnet Core.
Happy coding!
Thanks for the content. How to read the Byte[] and show the Image in UI?