The Bson document is directly supported by MongoDB itself, and the Bson document corresponds to the Bsondocument class in the official driver of C #:
var bsondoc = new bsondocument ()
{
[< Span style= "color: #a31515;" > "_id" " 123 " ,
[ "Name" ] = [ "age" ] = 32,
};
Because Bson is very similar to JSON itself, it is as easy as JSON to convert from. NET objects to each other.
PublicClassPerson
{
PublicStringId{Get;Set; } ="123";
PublicStringName{Get;Set; }
Public int age { getset; }
}
person = bsonserializer. Deserialize<person > (Bsondoc);
var doc = person. Tobsondocument
The additions and deletions of MongoDB itself are done directly for Bson documents:
var collection = database.GetCollection<BsonDocument>("foo");
collection.InsertOne(bsonDoc);
However, for ease of use, you can also use a strongly typed collection.
VarCollection = database.GetCollection<Person> ( "foo"
var person = new person ()
{
id = "365" ,
name = age = 32 ,
};
// Insert
Collection. insertone(person);
//Enquiry
Collection. Find(i-=-I-Name = = "Jack");
//Update
Collection. Replaceone(i + = Id = = "365", person);
//Delete
collection. Deleteone(i + = Id = = "365");
Because LINQ is supported, it is very convenient to use. Of course, you can also use the query function of MongoDB itself.
//Enquiry
result = collection. Find(Builders<person);. Filter. Eq(i=>i.Name, "Jack"). ToList();
//Update
Collection. replaceone(Builders<person). Filter. Eq(i + =Id, "365"), person);
//Update Partial fields
Collection.Updateone(builders<person>. filter. Eq , ),
builders<person>. update. Setage , 30));
// Delete
collection. deleteone(Builders<person). Filter. Eq(i + =Id, "365"));
Even if you can use the MONGDB command, you can also use the MONGO command directly, more concise.
//Enquiry
result = collection. Find("{Name: ' Jack '}"). ToList();
//Update
Collection. updateone("{Name: ' Jack '}", "{$set: {' age ': ' PNs '}}");
//Delete
collection. deleteone("{Name: ' Jack '}");
This approach is similar to SQL, very concise, but the loss of type checking, as to how to use, you need to see the specific situation.
Reference Documentation:
- Definitions and Builders
- MongoDB Tutorials
- MongoDB with C #
MongoDB simple to use-basic operation