MongoDB has several drivers. The open-source project of the Distributed File storage database MongoDB uses github.com/samus/mongodb-csharp. monogodb-csharpis not a strong driver and is easy to use. Use the norm C # driver that supports strong access to MongoDB. One difference between the norm driver and MongoDB-CSHARP is that norm uses a strongly typed class to operate the document class of MongoDB-CSHARP.
It's easy to use norm, just reference norm. dll. The following example is a consoleProgram:
Model class, representing the data saved to the database
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Using norm;
Namespace firstmongodb
{
Public Class Customer: ihaveidentifier
{
Public objectid _ id {Get; set ;}
Public string name {Get; set ;}
Public datetime lastorderutc {Get; set ;}
Public list <string> ordereditems {Get; set ;}
Public customer ()
{
Ordereditems = new list <string> ();
}
}
}
This is simple enough. Next we will connect to the database.
Public class mongodbdatacontext: idisposable
{
Private readonly extends queryprovider provider;
Public writable queryprovider provider
{
Get {return provider ;}
}
Public static string databasename {Get; set ;}
Public mongodbdatacontext ()
{
If (string. isnullorempty (databasename ))
{
Throw new invalidoperationexception ("You must set the static databasename property .");
}
Provider = new jsonqueryprovider (
New Mongo (databasename, "127.0.0.1", "27017", null ));
}
A database name, server address, and port need to be provided to connect to data using norm in winter. Refer to the above redCode.
Insert an object to the database
Private Static void insert ()
{
Customer c = new customer ();
C. Name = "Jake ";
C. lastorderutc = datetime. utcnow;
C. ordereditems. Add ("frappa ");
C. ordereditems. Add ("beer ");
C. ordereditems. Add ("redbull! ");
C. ordereditems. Add ("Wings ");
Using (mongodbdatacontext CTX = new mongodbdatacontext ())
{
CTX. Add (C );
}
}
Query a database using LINQ
Using (mongodbdatacontext CTX = new mongodbdatacontext ())
{
VaR query =
From C in CTX. MERs
Where C. Name = "Michael"
Orderby C. lastorderutc descending
Select C;
Foreach (VAR customer in query)
{
Console. writeline ("{0} bought {1 }",
Customer. Name,
Customer. ordereditems. firstordefault ()
);
}
}
Reference: Using MongoDB with the norm driver