‘bdfb4361-93b5-436d-bed2-2e56f3e60351’ is not a valid 24 digit hex string

I encountered this error while working with MongoDB Official C# Driver. This error occured when I was trying you insert some test data into a collection. Here’s the snap of error it shown

Later in the course I figured out i was using BsonReprentation Attribute to decorate the Bson data type as objectId.

When I changed the attribute to BsonId it started working fine. 

Below is my model before and after the changes.

Hope it helps somebody!

Getting Started With MongoDB and ASP.Net MVC4: Day 2

This article takes you a step further in getting started with MongoDB and ASP.NET series. Today, we will learn how to perform basic CRUD operations in MongoDB using Mongo Shell and a little about MongoDB C# Driver organization. The first two articles in this series are basically focused on MongoDB installation and how to use Mongo Shell to administer Mongo Server. In case you may want to read the Day 1 article, please refer to this link:

Let’s Start
So far you already know how to install and start Mongo Server (if you don’t then please follow the link above). Let’s start using Mongo Shell now and learn how to perform basic DB operations.

Okay, here I’ve a Mongo Server running in my local system on port 27017 and 28017 (the are default ports) as in the following:

And here’s the Mongo Shell:

You can see by looking at this figure that I’ve two collections (tables) in my MongoDB.

Before beginning with the Mongo Shell: there are many administrative and other commands available from the shell. If you want to check out what’s available then just type help and you can get specific help and more specific operations.

Creating Database in MongoDB using Mongo Shell

You already know from the previous article that the default database is “test” in MongoDB. If you want to create another db then just switch the db as you do in SQL Server using “use ” command syntax. It is the same in MongoDB also:

Command: Use myApp” or any name you like, it will switch or create a database if one doesn’t exist already.

Issue the “show dbs” command to see what databases are in there like I can see in the figure above.

Saving (Inserting) documents in MongoDB

As you know, MongoDB is schema-less and you don’t need to worry about creating tables (here we call them Collections), just insert the data into any collection. It will create the collection also if it doesn’t exist; very easy, isn’t it?

A MongoDB Document: Image courtesy (MongoDB Documentation)

MongoDB Collection: Image courtesy (MongoDB Documentation)

You use db..insert() for inserting data/documents into a MongoDB. “db” refers to the active database, so db.collection1 will refer to the current or active database that is myApp in our case. For example:

db.users.insert({username:”sunny”,password:”test”}) //if insert is successful it returns nothing.

The Command above will first create the collection “users” since our database “myApp” is empty and we don’t have any collection in there, and then it will insert the document. Later you can see the data inside a collection using the find() command on a collection.

Select documents from MongoDB

Syntax: db..find() // if you don’t specify any document to filter then it returns all the data.

E.g: db.users.find(); // this will select all documents from the collection.

Did you notice it automatically assigns an id to the document? Yes, it automatically creates a field “_id” with a GUID as a value for your document if it doesn’t contain one. If you’ve a field “_id” specified in your document, it’s pretty good then. You can see in the picture below that if I specify a field “_id” in my document, it doesn’t add it by itself:

It has another add-on function that shows the output of .find() in a formatted JSON format:

Add .pretty() after .find() and it will do the magic:

Deleting document from MongoDB

Syntax: db..remove() // here document contains field(s) that works as filter.

For example: db.users.remove({username:”manish”}) // and you see it’s gone.

So, this was all about giving you a basic idea of how the Mongo Shell works and how to perform administrative tasks using the shell. There’s brilliant documentation available on all the available commands with a nice tutorial on CRUD operations.

I suggest you refer to them if you want to master them.

The official MongoDB Driver for C#
Brief History
NoRM was popular for a while but now it’s no longer maintained hence not being used in new applications. There are also mongodb-csharp and simple-mongodb but they’ve both been inactive for several years. FluentMongo is the first library to provide LINQ support. Now that the LINQ support is built into the official driver, most of the apps have migrated to the official driver completely.

Ways to get/install the official MongoDB driver for C#
  1. The easiest and most popular is through Nuget. If you’re using Visual Studio, then right-click on your project in Solution Explorer and click “Manage Nuget Packages…” then search for “mongo” under the online tab and you’ll see “Official mongoDB C# Driver” listed on top. Click “Install” and wait for the installation to finish.

    If you use the Package Manager Console then you may want to install it using this command:

    Install-Package mongocsharpdriver

  2. There’s also a Zip archive with every release if you want to download them.
  3. Also there’s an MSI installer in case you want to do a Windows style installation from a setup file.
Here you can find the Zip archive and the MSI files: C#/.NET Driver Version 1.9.0 Release Notes

The purpose of this article was to teach MongoDB basic administrative operations using Mongo Shell and how to download/install the MongoDB C# official Driver. Since we’re going to learn how to use MongoDB in ASP.NET MVC, we will be using the MongoDB C# Official Driver instead of the Mongo Shell. On the next day, we will learn about the official MongoDB C# Driver’s organization and how it connects to a Mongo Server.

I hope you enjoyed this post… thanks for reading!!

Getting Started With MongoDB and ASP.Net MVC4: Day 1

Introduction and Goal

With this article I’m starting a step-by-step series on how to use MongoDB with ASP.NET MVC. In the course we will go from the basic to the advanced operations of MongoDB and gradually how to use it with ASP.NET MVC. 

What you will learn

  • You will learn the basics of MongoDB administration.
  • You’ll learn how the .Net driver is organized and how to use it to connect to the Mongo Server.
  • You’ll learn the fundamentals of how .Net types are serialized and stored in Mongo and how to customize the process to fit your specific needs.
  • You’ll learn how to create an update and remove data from your MVC Applications.
  • How to build models with rich behavior without the overhead of mapping  to our relational model.
  • You’ll learn how to use both LINQ and Mongo’s Query document style to query information from your application and how to combine them to build the most flexible of queries.
  • You’ll learn how to use GridFS to store files and associate them with documents in your MVC applications.
  • You’ll also learn how to avoid common pitfalls.
In this article “Day-1” of the series, we will learn how to get started with MongoDB. We will go through the introduction to MongoDB, why we should use MongoDB with ASP.NET and then download and instal it today. I chose to let you dive into the basics before moving towards the advanced lessons so that the series covers the novice developers as well or whosoever is not so familiar with MongoDB.

Introduction to MongoDB

MongoDB is from the family of emerging NoSQL or Not Only SQL databases. It’s a document type database where information is no longer stored in rows but rather as rich documents.

MongoDB uses BSON, very similar to JSON to store documents. BSON (or Binary JSON) is a binary encoding of JSON-like documents that MongoDB uses to store information in documents. It adds support for the Date and Binary (BinData) data type that isn’t supported in JSON.

Why use MongoDB in MVC?

  • Faster Development: unlike relational systems Mongo doesn’t require you to explicitly create a database, tables and columns; it’s all handled automatically by the very nature of flexible schemas. It significantly cuts the development effort.
  • Minimal Migrations: Mongo also minimizes data migrations.
  • Easier Collaborations: Fewer migrations mean much less pain sharing and merging changes with other developers.
  • Maintainable Design: With relational storage, building a rich model requires a lot of overhead to stitch together the results from many tables and then map that to separate models in your applications. This level of overhead either isn’t justifiable or is just too difficult to maintain. This leads developers to constrain the code to fit the relational model resulting in highly procedural code, duplication, foreign key identifiers, cascading deletes and so on, scrambling all the business logic. All of this results in an application that is very difficult to maintain.
  • Rich Behavior: As you start to create rich data models, you will find yourself adding rich behavior to those models as well. For example when order items are contained in an Order model, it’s easier to have the Order model calculate the total instead of doing the center Controller or otherwise.
  • Scalability: Mongo Architecture allows you to scale as your traffic increases.
  • GridFS: Mongo also has a fantastic system, GridFS, for storing querying and associating files with data in your application.

Last but not least, according to DB-Engine, the fifth most popular storage system and the number one NoSQL most popular solution (as of the date I’m writing this article, “2014-04-07”).

Let’s get started

In order to get started with MongoDB you need to first download and install it on your system. Visit MongoDB downloads URL: mongodb downloads and download the supported/desired version of MongoDB. As of now when I’m writing this article, the site looks like this:

The good part here is, you don’t need to install it at all. Just unzip the Zip file that you’ve downloaded and start exploring MongoDB, no installation at all. The contents inside the folder after you unzip it will look like this:

You can see the two executable files “mongo” and “mongod” (notice the additional “d” appended to mongo) that I’ve pointed to in the picture above. They’re the key of the entire play, at least “mongod.exe” if not both of them. 

mongod.exe is solely responsible for starting the MongoDB server whereas mongo.exe plays the role of the database client, using that you can access the MongoDB databases, collections and what not.
Procedure to start Mongo Server:
  1. Start a command prompt (cmd)
  2. Navigate to the MongoDB folder that you’ve unzipped.
  3. Enter “mongod.exe –dbpath db” , and hit Enter.
Here, the –dbpath parameter specifies the database path. You can use any other name if you don’t like “db” or you want some other name to be your database in there. If everything goes well then you’ll see the console screen something like this:

MongoDb uses two default ports for storage management: 27017 and 28017 (refer to the picture above). It says its “waiting for the connections on port 27017” and, “admin web console waiting for connections on port 28017”. It means you can manage a MongoDB database in two ways, one is by using a web browser and another is using any other client application.

Let’s give them a try. Fire up your browser, put http://localhost:28017 in the address bar and see what happens next. It will show you a dashboard kind of screen that contains information about the MongoDB Databases, their status and other info.

You can also use the REST URLs present in the top section to get various kinds of information related to the MongoDB database, but ensure you start MongoDB with the “-rest” parameter. For example:

“mongod.exe  –dbpath db -rest”
There are many other parameters available for use. You can always refer to the help manual in the console (cmd) using “mongod /?” or visit mongodb for more details.
Getting to the second executable file, it is the client that helps you talk to your MongoDB database and perform db operations. 
To start with, start another console then navigate to the MongoDb folder then enter “mongo.exe” and hit Enter. It will start a MongoDB Client console application. The MongoDB console is often called Mongo Shell.

You must have noticed that I didn’t specify any port but still it’s connected. It uses the default server (localhost) and port 27017 to connect to the MongoDB server if you don’t specify any server address and port. The default database it will try to connect to is “test”.

Make sure the MongoDB server is running, otherwise the client will not be able to communicate and eventually will throw an error that it couldn’t connect to the MongoDB server:

What next?
In the next article we will learn how to perform basic CRUD operations in MongoDB and much more. The next day will get you started with reading and writing data to MongoDB.

Getting Started with MongoDB and ASP.NET: Day 2

I hope you enjoyed this post… thanks for reading… follow for more 🙂

What is MongoDB?

MongoDB is a NoSQL DataBase whose main features include document-oriented storage, full index support, replication and high availability, auto-sharding, querying, fast in-place updates, Map/Reduce, and GridFS.

MongoDB addresses volume, variety, and velocity of data that organizations increasingly have to deal with in the following ways:

  • Massive Data Volumes: MongoDB is designed to scale horizontally on commodity hardware, making it easy to add nodes to a cluster as data volumes and velocities increase. 

  • Real-time demands: As well as supporting the fundamental querying that you’d expect from an operational database, MongoDB’s native Map/Reduce and aggregation framework support real-time analytics and insights.
  • Rapid evolution: An organization’s needs should change as it responds to the information gained from all the data it has access to. MongoDB’s dynamic document schema enables applications to evolve as the needs of the business evolve.
  • Document-Oriented Storage: MongoDB is a document database, meaning that it stores data in semi-structured, JSON-style documents in collections, rather than storing data in tables that consist of rows and columns, as is done with relational databases such as MySQL. MongoDB collections are similar to tables in relational databases, although collections are a lot less rigid.