Mongo db rev001.

41
MongoDB in C# By Rich Helton January 01, 2015 Buy “Mastering NserviceBus with Persistence”

Transcript of Mongo db rev001.

Page 1: Mongo db rev001.

MongoDB in C#

By Rich HeltonJanuary 01, 2015

Buy “Mastering NserviceBus with Persistence”

Page 2: Mongo db rev001.

What is MongoDB MongoDB is a cross-platform document-oriented database. http://en.wikipedia.org/wiki/MongoDB➢ This means that it is NoSQL, not utilizing the

relational SQL commands, but utilizing JSON-like documents to query the database.

➢ The JSON-like documents are BSON, Binary JSON.

➢ MongoDB is free and open source.➢ http://www.mongodb.org

Page 3: Mongo db rev001.

What is MongoDB

➢ MongoDB is a cross-platform document-oriented database. http://en.wikipedia.org/wiki/MongoDB

➢ This means that it is NoSQL, not utilizing the relational SQL commands, but utilizing JSON-like documents to query the database.

➢ MongoDB is free and open source. http://www.mongodb.org

Page 4: Mongo db rev001.

The Motivation

● Sometimes using a full Microsoft SQL Server installation, with maintenance for databases, may be a little overkill for something as simple as keeping track of a file history table.

● The need for access control is still needed for basic security, so something more than a File I/O is required.

Page 5: Mongo db rev001.

Installation

● Installation instructions can be found to install the correct version by checking the OS from http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/

● The download page of the installations for Windows, OSX, Solaris and Linux can be found at http://www.mongodb.org/downloads

● We can optionally move the downloaded files to “C:\mongodb\”.

Page 6: Mongo db rev001.

Installation MSI's

● Alternately, you can just use the MongoDB MSI file to install the program into the “C:\Program Files\MongoDB” directory.

● For Win32, http://dl.mongodb.org/dl/win32/i386

● For Win64, http://dl.mongodb.org/dl/win32/x86_64

Page 7: Mongo db rev001.

Startup

● An data directory needs to be created to store the database, for example “md \data\db”, which “\data\db” is the default directory for mongod.

● Running “C:\mongodb\bin\mongod.exe” will now create the database.

● The “--auth” argument can be used to force authentication into the server.

Page 8: Mongo db rev001.

Running mongod.exe

Page 9: Mongo db rev001.

There are many tools for MongoDB

➢ There are many admin tools, some can be found at http://docs.mongodb.org/ecosystem/tools/administration-interfaces/

➢ One of the admin tools that supports multiple platforms and runs in Java is Umongo, found at http://edgytech.com/umongo/

Page 10: Mongo db rev001.

Viewing the new database in UMongo

After downloading Umongo, we run the applications with the default settings to see the new database:

Page 11: Mongo db rev001.

Running as a Service

l To run MongoDB as a service, we need a config file and we will use the -install option on this config file.

l We will create a log directory in the “C:\data\db” directory.

Page 12: Mongo db rev001.

Creating and starting the serviceRunning “mongod

--logpath=C:\data\db\log\mongo.log --install” as administrator in the command

prompt:

Page 13: Mongo db rev001.

Viewing the service

After installing the service, we can see the service running:

Page 14: Mongo db rev001.

A recap of some of the exe's:

● mongo.exe – runs the database shell.● mongod.exe – the core database.● mongos.exe – auto sharding process.● mongodump.exe – dump/export utility. ● mongorestore.exe – restore/import utility.

Page 15: Mongo db rev001.

Start the C#

Page 16: Mongo db rev001.

We will create a Command program MongoDBConsoleApp1

Page 17: Mongo db rev001.

NuGet the mongocsharpdriver

https://www.nuget.org/packages/mongocsharpdriver/

Page 18: Mongo db rev001.

No matter the database, there needs to be a connectionstring

l Add an App.config with the “<add key="connectionString" value="Server=localhost:27017"/>”. The default port for MongoDB is port 27017.

Page 19: Mongo db rev001.

Starting the DB connection

l We will get the connectionstring, and connect to the database.

Page 20: Mongo db rev001.

BSON and the DB

In order to perform CRUD operations on the database, a BsonCollection is used to map to the table. The table is really a collection of documents. The documents being name/value pairs. Here, we have an insert of a document.

Page 21: Mongo db rev001.

More on BSON

BSON is Binary JSON. It is a name-value pair, in which the value could be many different data types.

More on BSON can be found at http://en.wikipedia.org/wiki/BSON

Page 22: Mongo db rev001.

After the insert, verify After the insert, we can verify the data in UMongo.

Here, we see that a document was created in the FileHistory collection.

We can also export the data to a text file.

Page 23: Mongo db rev001.

Viewing the exported file

Page 24: Mongo db rev001.

Code to read the collection

A table is just a collection of documents. Each document has a name/value pair.

We walk through the collection reading the name-value pair.

Page 25: Mongo db rev001.

Updating the collection

➢ To update the collection, find the value in the collection, change it, and save it in the collection.

Page 26: Mongo db rev001.

Deleting a document

➢ To remove a document, a query has to be developed that matches a name-value pair.

Page 27: Mongo db rev001.

Deleting a collection (table)

➢ To remove a collection, a drop need only be performed on the collection.

Page 28: Mongo db rev001.

static void Main(string[] args) { // get the App.config Connection String string connString = ConfigurationManager.AppSettings["connectionString"]; // Get the client connection var client = new MongoClient(connString); // Get the MongoServer Object var server = client.GetServer();

// Gets a link to the DB, will create with first insert MongoDatabase myDatabase = server.GetDatabase("FileHistory");

// Create a BsonDocument list for the Table MongoCollection<BsonDocument> filesReceivedTable = myDatabase.GetCollection<BsonDocument>("BankFilesReceieved"); // Create an individual Table row with the fields BsonDocument filesReceived = new BsonDocument { { "DateReceived", DateTime.Now }, { "FileName", "BankFile1.txt" }}; // Insert into table filesReceivedTable.Insert(filesReceived); // Get the table collection MongoCollection<BsonDocument> updateTable = myDatabase.GetCollection<BsonDocument>("BankFilesReceieved"); // Walk through each document updating the name-value pair. foreach (var filesRead in updateTable.FindAll()) { foreach (var elements in filesRead.Elements) { if (elements.Name == "FileName") { elements.Value = "BankNameChanged.txt"; updateTable.Save(filesRead); } } }

Page 29: Mongo db rev001.

// Get the table collection MongoCollection<BsonDocument> deletingRows = myDatabase.GetCollection<BsonDocument>("BankFilesReceieved"); // Remove on query where a name = a specific value deletingRows.Remove(Query.EQ("FileName","BankNameChanged.txt"));

// Get the table collection MongoCollection<BsonDocument> readingTable = myDatabase.GetCollection<BsonDocument>("BankFilesReceieved"); // Walk through each document reading the name-value pair. foreach (var filesRead in readingTable.FindAll()) { foreach (var elements in filesRead.Elements) { Console.WriteLine("Name :" + elements.Name); Console.WriteLine("Value :" + elements.Value); } } // Get the table collection MongoCollection<BsonDocument> deletingTable = myDatabase.GetCollection<BsonDocument>("BankFilesReceieved"); // Delecting the table deletingTable.Drop();

}

Page 30: Mongo db rev001.

Mongo Shell

Page 31: Mongo db rev001.

Mongo Shell● The mongo.exe is used to execute shell commands. http://docs.mongodb.org/manual/reference/mongo-shell/

● The shell commands can be used to show databases, users, collections, and also create the same.

Page 32: Mongo db rev001.

Adding a user

● Can be created using the “db.addUser(“user”,”password”) in the mongo shell.

Page 33: Mongo db rev001.

In C#, adding a user would be similar to:

Page 34: Mongo db rev001.

In C#, executing the function could be done as:

Page 35: Mongo db rev001.

In C#, finding all users would be similar to:

Page 36: Mongo db rev001.

In C#, finding all users would be similar to:

Page 37: Mongo db rev001.

User Roles

● Just because a user is added, doesn't mean that the user has assigned roles.

● We can see the roles to be added in the NoSQL Manager for MongoDB.

Page 38: Mongo db rev001.

Mongo C# Driver

Page 39: Mongo db rev001.

The Mongo C# driver ● The documentation can be found at http://docs.mongodb.org/ecosystem/drivers/csharp/

● This was the nuget driver that we installed earlier as version 1.9.2.There are c-sharp community projects found

at http://docs.mongodb.org/ecosystem/drivers/csharp-community-projects/

, one of which is MongoCola.

Page 40: Mongo db rev001.

MongoCola● MongoCola is an c# open source Mongo Admin tool. ● The c-sharp source code for MongoCola can be found at

https://github.com/magicdict/MagicMongoDBTool

Page 41: Mongo db rev001.

Some Admin ToolsHomepages

● MongoCola Homepagehttp://osdig.com/project/index/id/22703.html#.VKljkF1ietV

● No-SQL Manager for MongoDBhttp://www.mongodbmanager.com/