Introduction to MongoDb with .NET part 18: insertions in the MongoDb driver

Introduction

In the previous post we looked at 4 functions related to refining our searches: limiting, skipping, sorting and counting. We saw that they were quite easy and straightforward to use. The sort function was the most versatile in the sense that there are multiple ways to build sort definitions for our queries.

In this post we’ll look at how to insert documents via the MongoDb driver.

Insertions

Insertions are represented by the following functions in the driver: InsertOne, InsertMany, InsertOneAsync and InsertManyAsync. You can probably guess what they are for. InsertOne inserts a single document synchronously whereas InsertOneAsync does the same in an awaitable manner. InsertMany and InsertManyAsync are used for bulk insertions to insert many documents at the same time.

Let’s try and add a new restaurant document:

ModelContext modelContext = ModelContext.Create(new ConfigFileConfigurationRepository(), new AppConfigConnectionStringRepository());
RestaurantDb newRestaurant = new RestaurantDb();
newRestaurant.Address = new RestaurantAddressDb()
{
	BuildingNr = "120",
	Coordinates = new double[] {22.82, 99.12},
	Street = "Whatever",
	ZipCode = 123456
};
newRestaurant.Borough = "Somewhere in Thailand";
newRestaurant.Cuisine = "Thai";
newRestaurant.Grades = new List<RestaurantGradeDb>()
{
	new RestaurantGradeDb() {Grade = "A", InsertedUtc = DateTime.UtcNow, Score = "7" },
	new RestaurantGradeDb() {Grade = "B", InsertedUtc = DateTime.UtcNow, Score = "4" }
};
newRestaurant.Id = 883738291;
newRestaurant.Name = "RandomThai";
						
modelContext.Restaurants.InsertOne(newRestaurant);

We construct a new RestaurantDb object and dress it up a little. We then just call the InsertOne function. Note that we didn’t need to provide an ObjectId in code, it will be generated for us by MongoDb.

In case you’d like to provide a new Objectid in code you can do it as follows:

newRestaurant.MongoDbId = ObjectId.GenerateNewId();

A simple query in a MongoDb client shell with…

db.restaurants.find({"name" : "RandomThai"}).pretty()

…will find our Thai restaurant immediately:

{
        "_id" : ObjectId("571fc46690f5280e2c17d775"),
        "address" : {
                "building" : "120",
                "coord" : [
                        22.82,
                        99.12
                ],
                "street" : "Whatever",
                "zipcode" : 123456
        },
        "borough" : "Somewhere in Thailand",
        "cuisine" : "Thai",
        "grades" : [
                {
                        "date" : ISODate("2016-04-26T19:41:23.904Z"),
                        "grade" : "A",
                        "score" : "7"
                },
                {
                        "date" : ISODate("2016-04-26T19:41:23.904Z"),
                        "grade" : "B",
                        "score" : "4"
                }
        ],
        "name" : "RandomThai",
        "restaurant_id" : 883738291
}

Just FYI: I got those coordinates from this site which generates random geo-coordinates. The first location on any of the continents was in Thailand so I picked it for this demo.

Let’s also insert demonstrate the usage of InsertMany to insert 2 restaurants in the same request:

RestaurantDb newPakistaniRestaurant = new RestaurantDb();
newPakistaniRestaurant.Address = new RestaurantAddressDb()
{
	BuildingNr = "12A",
	Coordinates = new double[] { 31.135, 71.24 },
	Street = "New Street",
	ZipCode = 9877654
};
newPakistaniRestaurant.Borough = "Somewhere in Pakistan";
newPakistaniRestaurant.Cuisine = "Pakistani";
newPakistaniRestaurant.Grades = new List<RestaurantGradeDb>()
{
	new RestaurantGradeDb() {Grade = "A", InsertedUtc = DateTime.UtcNow, Score = "9" },
	new RestaurantGradeDb() {Grade = "C", InsertedUtc = DateTime.UtcNow, Score = "3" }
};
newPakistaniRestaurant.Id = 457656745;
newPakistaniRestaurant.Name = "PakistaniKing";

RestaurantDb newMexicanRestaurant = new RestaurantDb();
newMexicanRestaurant.Address = new RestaurantAddressDb()
{
	BuildingNr = "2/C",
	Coordinates = new double[] { 24.68, -100.9 },
	Street = "Mexico Street",
	ZipCode = 768324523
};
newMexicanRestaurant.Borough = "Somewhere in Mexico";
newMexicanRestaurant.Cuisine = "Mexican";
newMexicanRestaurant.Grades = new List<RestaurantGradeDb>()
{
	new RestaurantGradeDb() {Grade = "B", InsertedUtc = DateTime.UtcNow, Score = "10" }
};
newMexicanRestaurant.Id = 457656745;
newMexicanRestaurant.Name = "MexicanKing";

List<RestaurantDb> newRestaurants = new List<RestaurantDb>()
{
	newPakistaniRestaurant,
	newMexicanRestaurant
};

modelContext.Restaurants.InsertMany(newRestaurants);

A simple JSON query in the Mongo shell…:

db.restaurants.find({$or : [{"name" : "PakistaniKing"}, {"name" : "MexicanKing"}]}).pretty()

…will find both of them:

{
        "_id" : ObjectId("571fc8d290f5282a5077895f"),
        "address" : {
                "building" : "12A",
                "coord" : [
                        31.135,
                        71.24
                ],
                "street" : "New Street",
                "zipcode" : 9877654
        },
        "borough" : "Somewhere in Pakistan",
        "cuisine" : "Pakistani",
        "grades" : [
                {
                        "date" : ISODate("2016-04-26T20:00:18.083Z"),
                        "grade" : "A",
                        "score" : "9"
                },
                {
                        "date" : ISODate("2016-04-26T20:00:18.083Z"),
                        "grade" : "C",
                        "score" : "3"
                }
        ],
        "name" : "PakistaniKing",
        "restaurant_id" : 457656745
}
{
        "_id" : ObjectId("571fc8d290f5282a50778960"),
        "address" : {
                "building" : "2/C",
                "coord" : [
                        24.68,
                        -100.9
                ],
                "street" : "Mexico Street",
                "zipcode" : 768324523
        },
        "borough" : "Somewhere in Mexico",
        "cuisine" : "Mexican",
        "grades" : [
                {
                        "date" : ISODate("2016-04-26T20:00:18.083Z"),
                        "grade" : "B",
                        "score" : "10"
                }
        ],
        "name" : "MexicanKing",
        "restaurant_id" : 457656745
}

This is pretty much it as far as insertions are concerned. There’s another important topic around insertions called the write concern but we’ll discuss that separately later on.

In the next post we’ll look at updates.

You can view all posts related to data storage on this blog here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to Introduction to MongoDb with .NET part 18: insertions in the MongoDb driver

  1. MarkusR says:

    Man oh man your tutorials are great! What would the best way to add a little image to the restaurant such as a logo? Tack så mycket 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: