Concepts
- NoSql Database
- Database - Like SqlServer Databases
- Collection - Like SqlServer Tables
- Document - Like Table Rows
- You don't need to define schema, columns or relations in MongoDb, It'll just work whatever you try to insert inside a collection.
- Documents/Rows don't have to be consistent in same collection. One document can have large json with lots of attribute and other can just have single property totally unrelated to the first document.
- You can't define relations, that means data will be redundant and repetitive. But each document will have data in itself. That benefits in fast crud operations. Thats why NoSql is for.
- Its trade for speed vs space and consistency.
- Create a new object or class and insert into the collection. If collection or database doesn't exist; It will create for you on insert.
- It uses BSON object as backend. its just Json with different name.
Installation
- You can use mongodb atlas - Cloud hosted MongoDB on multiple platforms
- Or You can install locally via this link. It'll give you MongoDB Compass (like SqlServer Management Studio for mongo) and Mongo Db Database. You should put mongo folder, usually located at C:\Program Files\MongoDB\Server\<Your Version>\bin, to environment variables to use shell.
- After installation it'll probably require a reboot.
- First time your compass should look like this
- Click Connect, Leave Default localhost settings. It should work.
Yeaaah!. MongoDB is working on your local now. Have fun!.
Connecting Your local
- Create an emtpy console app
- Install MongoDB.Driver from Nuget Package Manager
- Put this code in your Program.cs Main Function
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("BookstoreDb");
_books = database.GetCollection<Book>("Books");- Create the Model
- Resolve Imports and Debug to check you should get empty books
public class Book
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("Name")]
[JsonProperty("Name")]
public string BookName { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public string Author { get; set; }
}
_books.InsertOne(new Book() { Author = "Whoevery", BookName = "Clean Code",
Category = "Programming", Price = 12 });
- Above code should insert a document and now get should return some value
- Now you know how to create database, collection and a document
- Go to compass; if you have connected Hit refresh. You should see your data now.