First look MongoDB
First look MongoDB
I have used SQL through out my life and its time to look at different type of databases. Today I am going to look at MongoDB, which is a Non SQL database. So in this blog, I will convert the blog database from SQL to MongoDB, lets see how this goes.

Current database records to MongoDB documents
Currently the blog SQL database uses the below tables to store a record(s) for a single blog entry
  • blogs, blogs_revisions
  • blog_relatedLinks
  • comments
  • users
  • viewer

Going forward using MongoDB, all the data from each table will be be compiled into a single document for each blog. All blog documents will be in a single collection.

Data object
Below is the data class of the package the SQL database blog record will be mapped too and then this will be used as the MongoDB collection

public class MongoDBBlogDataPackage
{
public string Title { get; set; }
public string Name { get; set; }
public string MetaTag { get; set; }
public DateTime DateCreated { get; set; }
public Nullable< DateTime > DatePublished { get; set; }
public bool Active { get; set; }
public bool Published { get; set; }
public List< BlogRelatedLinkDataClass > RelatedLinks { get; set; }
public List< CommentDataClass > Comments { get; set; }
public List< MongoDBBlogRevisionDataPackage > Revisions { get; set; }
}

First steps would create the logic to create this data object from the database and then I will look at creating the MongoDB logic.

using (var context = new blogEntity())
{

foreach(var result in context.blogs.ToList())
{
var data = new DataObjects.MongoDBBlogDataPackage()
{
Title = result.title,
Active = result.active,
DateCreated = result.created,
DatePublished = result.publishedDate,
MetaTag = result.metaTag,
Name = result.name,
Published = result.published,
Comments = result.comments.Select(s => new DataObjects.CommentDataClass()
{
Body = s.body,
CreatedBy = "Unknown",
RenderBody = s.rendered,
CreatedDate = s.created.Value
}).ToList(),
RelatedLinks = result.blog_RelatedLink.Select(s => new DataObjects.BlogRelatedLinkDataClass()
{
Description = s.description,
Order = s.order,
Title = s.title,
URL = s.url
}).ToList(),
Revisions = result.blog_revision.Select(s => new DataObjects.MongoDBBlogRevisionDataPackage()
{
Active = s.active.Value,
Created = s.created,
Published = s.published,
PublishedDate = s.publishedDate,
Raw = s.raw,
Rendered = s.rendered,
Sketleton = s.sketleton

}).ToList()
};
collection.Add(data);
}


MongoDB Communication
Now I need to go to MongoDB.com to create a Free account, which will allow me to create a blog database and Blog Entity collection. After I have a database I need to add the Libraries and code to communicate with the new database.
The library (NuGet Plugin) I will use is MongoDB.Driver . Once installed, I need to get the connection string from MongoDB.Com. (One of the YouTub linked videos will show you how to do this, if you don't know already)
Using the simple code snippet below, where I create the MongoClient (This is the Context of the MongoDB and you add the connection string to this), MongoDatabase (This is the main database which the user in the connection string can connect too.) and MongoCollection (This is the collection table you want to manipulate or view)
The [Username] and [Password] needs to be your username and password set against your DB on MongoDB

private string connectionString = "mongodb+srv://[Username]:[Password]@cluster0.40mbnws.mongodb.net/?retryWrites=true&w=majority";
private string databaseName = "Blog";
private string collectionName = "BlogEntries";
private MongoClient client;
private IMongoDatabase database;
private IMongoCollection< DataObjects.MongoDBBlogDataPackage > collection;
public SimpleTest()
{
//Needs using MongoDB.Driver;
client = new MongoClient(connectionString);
database = client.GetDatabase(databaseName);
//Needs using MongoDB.Bson;
collection = database.GetCollection< DataObjects.MongoDBBlogDataPackage >(collectionName);
}


MongoDBBlogDataPackage Dataobject
I've done some tweaks to my data object, so it can be map correctly to the collection. Really all I needed to do was add an Id and some attributes.
 
[BsonIgnoreExtraElements]//This will Ignore anything that is in the collection, which we do not care about
public class MongoDBBlogDataPackage
{
[BsonId]//This needs using MongoDB.Bson.Serialization.Attributes; added to the class (23 mins in vid)
public ObjectId Id { get; set; }//ObjectId needs using MongoDB.Bson;
[BsonElement("Title")]
public string Title { get; set; }
[BsonElement("Name")]
public string Name { get; set; }
[BsonElement("MetaTag")]
public string MetaTag { get; set; }
[BsonElement("DateCreated")]
public DateTime DateCreated { get; set; }
[BsonElement("DatePublished")]
public Nullable< DateTime > DatePublished { get; set; }
[BsonElement("Active")]
public bool Active { get; set; }
[BsonElement("Published")]
public bool Published { get; set; }
[BsonElement("RelatedLinks")]
public List< BlogRelatedLinkDataClass > RelatedLinks { get; set; }
[BsonElement("Comments")]
public List< CommentDataClass > Comments { get; set; }
[BsonElement("Revisions")]
public List< MongoDBBlogRevisionDataPackage > Revisions { get; set; }
}


Amending the data
Now we have the Client and collection set up, its time to look at inserting, editing and deleting records.

Insert documents
I've been using C# and Linq logic for sometime and the best thing, I can use it with MongoDB as well. Below is an example of how I can use Linq to insert data

public void Insert()
{
var records = Models.Blog.Queries.MonogDataPackageQuery.CreateDataPackage();
foreach (var record in records)
collection.InsertOne(record);
}

Get documents
I've been using C# and Linq logic for sometime and the best thing, I can use it with MongoDB as well. Below is an example of how I can use Linq to access

public void Get()
{
//This is a list document object of all active records
var activeRecords = collection.Find(x => x.Active.Equals(true)).ToList();
//This is a list document object of all active records
var disableRecords = collection.Find(x => x.Active.Equals(false)).ToList();
//This will get a First record
var firstRecord = collection.Find(x => x.Name.Equals("Visual-Studio-Team-Foundation-Service-Agile-Bug-Log")).FirstOrDefault();
//This will get a single record
var singleRecord = collection.Find(x => x.Active.Equals(true) && x.Name.Equals("Visual-Studio-Team-Foundation-Service-Agile-Bug-Log")).SingleOrDefault();
//This will get a null record as this name does not exists
var nullRecord = collection.Find(x => x.Name.Equals("Visual-Studio-Team-Foundation-Service-Agile-Bug-Log-1")).FirstOrDefault();
}

Update documents
This is not really Linq, but its the only way I see this been done. You Set the field you want to update in the document as a update. Then create a filter object, to say which document you want to do this change to and then Update your collection.

public void Update()
{
var update = Builders< DataObjects.MongoDBBlogDataPackage >.Update.Set(x=>x.MetaTag, "Updated1");
var filter = Builders< DataObjects.MongoDBBlogDataPackage >.Filter.Eq(x => x.Name, "Visual-Studio-Team-Foundation-Service-Agile-Bug-Log");
collection.UpdateOne(filter, update);

}


Delete documents
This is not really Linq, but its the only way I see this been done. You create a filter object, to say which document you want to do this delete and then delete from your collection.

public void Delete()
{

var filter = Builders< DataObjects.MongoDBBlogDataPackage >.Filter.Eq(x => x.Name, "Visual-Studio-Team-Foundation-Service-Agile-Bug-Log");
collection.DeleteOne(filter);
}



Full class
Below is the full class for each element above (apart from data object)

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

namespace Models.MondgoDB
{
public class SimpleTest
{
private string connectionString = "mongodb+srv://[Username]:[Password]@cluster0.40mbnws.mongodb.net/?retryWrites=true&w=majority";
private string databaseName = "Blog";
private string collectionName = "BlogEntries";
private MongoClient client;
private IMongoDatabase database;
private IMongoCollection< DataObjects.MongoDBBlogDataPackage > collection;
public SimpleTest()
{
//Needs using MongoDB.Driver;
client = new MongoClient(connectionString);
database = client.GetDatabase(databaseName);
//Needs using MongoDB.Bson;
collection = database.GetCollection< DataObjects.MongoDBBlogDataPackage >(collectionName);
}


public void Insert()
{
var records = Models.Blog.Queries.MonogDataPackageQuery.CreateDataPackage();
foreach (var record in records)
collection.InsertOne(record);
}

public void Get()
{
//This is a list document object of all active records
var activeRecords = collection.Find(x => x.Active.Equals(true)).ToList();
//This is a list document object of all active records
var disableRecords = collection.Find(x => x.Active.Equals(false)).ToList();
//This will get a First record
var firstRecord = collection.Find(x => x.Name.Equals("Visual-Studio-Team-Foundation-Service-Agile-Bug-Log")).FirstOrDefault();
//This will get a single record
var singleRecord = collection.Find(x => x.Active.Equals(true) && x.Name.Equals("Visual-Studio-Team-Foundation-Service-Agile-Bug-Log")).SingleOrDefault();
//This will get a null record as this name does not exists
var nullRecord = collection.Find(x => x.Name.Equals("Visual-Studio-Team-Foundation-Service-Agile-Bug-Log-1")).FirstOrDefault();


}


public void Update()
{
var update = Builders< DataObjects.MongoDBBlogDataPackage >.Update.Set(x=>x.MetaTag, "Updated1");
var filter = Builders< DataObjects.MongoDBBlogDataPackage >.Filter.Eq(x => x.Name, "Visual-Studio-Team-Foundation-Service-Agile-Bug-Log");
collection.UpdateOne(filter, update);

}


public void Delete()
{
var filter = Builders< DataObjects.MongoDBBlogDataPackage >.Filter.Eq(x => x.Name, "Visual-Studio-Team-Foundation-Service-Agile-Bug-Log");
collection.DeleteOne(filter);
}
}
}

Related Links

Buy me a coffeeBuy me a coffee

Latest blogs

Buy me a coffeeBuy me a coffee
Created: 05/07/2022 Total Comment: 0

Comments

(Not Displayed)
Human validation
Enter 3030 number, before submitting to confirm your human
Buy me a coffeeBuy me a coffee

[Home] [All Blogs] [Contact] [Me]
Buy me a coffeeBuy me a coffee