Asp Net Core Fro MongoDB Part1, fromongodb
"No time! "
The following articles are used to learn mongoDB:
Using MongoDB with ASP. NET Core-Part II (Implementation)
From https://www.janaks.com.np/using-mongodb-with-aspnet-core-ii/>
MongoDB Study Notes (2) use the samus driver to perform basic data operations
From http://www.cnblogs.com/lipan/archive/2011/03/08/1977691.html>
For more information about how to install and debug MongoBD, see the preceding two articles.
Before proceeding to the following operations, make sure that the MongoDB service has been enabled. You do not know how to enable the service. Please refer to the MongoDB installation and configuration.
Download the driver and create a console Project (. net Core)
Add references to MongoDB. dll and search for MongoDB (current version 2.4.3) by nuget ).
Private IMongoDatabase _ database; Private string _ connStr = "mongodb: // localhost: 27017 "; Private string _ dbName = "VesselDB "; |
// Create a database proxy class and link to the database
Public VesselRepository () { Var client = new Consumer client (_ connStr ); _ Database = client. GetDatabase (_ dbName ); } |
// Define an object
Public class Vessel { [BsonId] Public int IMO {get; set ;} [BsonElement ("VesselName")] Public string Name {get; set ;} [BsonElement ("PortOfRegistry")] Public string Registry {get; set ;} [BsonElement ("YearofBuilt")] Public DateTime YearOfBuilt {get; set ;} } |
// Add, modify, delete, and query methods
// AddMethod Public void AddVessel (Vessel vsl) { _ Database. GetCollection <Vessel> ("Vessels"). InsertOne (vsl ); } // DeletedMethod Public void DeleteVessel (string vslName) { Var filter = Builders <Vessel>. Filter. Eq (vsl => vsl. Name, vslName ); _ Database. GetCollection <Vessel> ("Vessels"). DeleteOne (filter ); } // Getmentodd Public IEnumerable <Vessel> GetAllVessels () { Return _ database. GetCollection <Vessel> ("Vessels"). Find (FilterDefinition <Vessel>. Empty). ToList (); } // UpdateMethod Public void UpdateVessel (int imo, Vessel vsl) { Var filter = Builders <Vessel>. Filter. Eq (v => v. IMO, imo ); Var update = Builders <Vessel>. Update . Set (v => v. Name, vsl. Name) . Set (v => v. Registry, vsl. Registry) . Set (v => v. YearOfBuilt, vsl. YearOfBuilt ); _ Database. GetCollection <Vessel> ("Vessels"). UpdateOne (filter, update ); } |
It works perfectly.