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");varperson =NewPerson () {Id="365", Name="Jack", Age= +,}; //Insertcollection. Insertone (person); //EnquiryCollection. Find (i = I.name = ="Jack"); //UpdateCollection. Replaceone (i = i.id = ="365", person); //DeleteCollection. Deleteone (i = 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.
//Enquiryresult = collection. Find (BUILDERS<PERSON>. Filter.eq (I=>i.name,"Jack")). ToList ();//UpdateCollection. Replaceone (BUILDERS<PERSON>. Filter.eq (i = i.id,"365"), person); //Update Partial fieldsCollection. Updateone (BUILDERS<PERSON>. Filter.eq (i = i.id,"365"), Builders<person>. Update.set (i = i.age, -)); //DeleteCollection. Deleteone (BUILDERS<PERSON>. Filter.eq (i = i.id,"365"));
Even if you can use the MONGDB command, you can also use the MONGO command directly, more concise.
//Enquiryresult = collection. Find ("{Name: ' Jack '}"). ToList (); //UpdateCollection. Updateone ("{Name: ' Jack '}","{$set: {' age ': ' PNs '}}"); //DeleteCollection. Deleteone ("{Name: ' Jack '}");
这种方式类似Sql,非常简洁,但是失去了类型检查,至于如何选择,则需要看具体场合了。
Reference Documentation:
- Definitions and Builders
- MongoDB Tutorials
- MongoDB with C #
MongoDB simple to use-basic operation