Several ways to retrieve data using MongoDB in C #
To retrieve an object:
[Bsonignoreextraelements] Public classUsermongomodel {/// <summary> /// /// </summary> Public LongUserID {Set; Get; } Public stringUserName {Get; Set; } /// <summary> /// /// </summary> Public intusertype {Set; Get; } /// <summary> ///0-Delete 1-not deleted/// </summary> Public intIsValid {Set; Get; } /// <summary> /// /// </summary> PublicDateTime Createtime {Set; Get; } }
View Code
Where Bsonignoreextraelements is best added to the object, because some of MongoDB's serialization methods are different from C #, such as the date format, the time saved in MongoDB is automatically deducted for 8 hours (local time). When you use Bsonignoreextraelements to mark an object, the retrieved time attribute does not need to be processed again.
There are four types of mongoclient initialization:
Mongoclient (); Mongoclient (connectionString); Mongoclient (mongoclientsettings); Mongoclient (Mongourl);
View Code
My side uses both ConnectionString and Mongourl methods. where connectionstring the value of the link string: Mongodb://uname:[email protected]:p ort/database. Where uname is the user name, PWD is the password. The HostIP is the server IP address, port is the port number, and database is the name.
So there is Var client=new mongoclient (Mongodb://uname:[email protected]:p ort) or
Mongourl url = new Mongourl (mongodb://uname:[email protected]:p ort/database);
var client = new Mongoclient (URL);
method to get the database name string databaseName = URL. DatabaseName;
Get database objects:
var db=client. Getdatabase (DatabaseName);
Get the corresponding table data:
var collection=db. Getcollection<tdocument> (tablename)
Where tdocument can be the corresponding Usermongomodel can also be bsondocument and so on. The tablename is the corresponding table name.
In the back we use DB and collection to represent the corresponding libraries and tables
1 simplest search, no search criteria
var filter = Builders<usermongomodel>. Filter.empty;
var result = collection. Find<usermongomodel> (filter);
2 If it is the total number of retrieved data
var filter = Builders<usermongomodel>. Filter.empty;
Var sum= collection. Find<usermongomodel> (filter). Count ();
MongoDB Retrieval Statements