MongoDB is simple to use - basic operations

MongoDB itself directly supports Bson documents, and Bson documents correspond to the BsonDocument class in the official C# driver:

var bsonDoc = new BsonDocument()
{
    ["_id"]  = "123",
    ["Name"] = "Jack",
    ["Age"]  = 32,
};

Since Bson is very similar to Json itself, it is very easy to convert to and from .net objects like Json.

public class Person
{
    public string Id   { getset; } = "123";
    public string Name { getset; }
    public int    Age  { getset; }
}

var person = BsonSerializer.Deserialize<Person>(bsonDoc);
var doc = person.ToBsonDocument();

MongoDB's own additions, deletions, and changes are performed directly on Bson documents:

var collection = database.GetCollection<BsonDocument>("foo");
collection.InsertOne(bsonDoc);

But for ease of use, strongly typed collections can also be used.

var collection = database.GetCollection<Person>("foo");

var person = new Person ()
{
    Id   = "365",
    Name = "Jack",
    Age  = 32,
};
                                                                                                                    
// Insert 
collection.InsertOne(person);
                                        
//查询
collection.Find(i => i.Name == "Jack");
                                                        
//更新
collection.ReplaceOne(i => i.Id == "365", person);
                                                        
//删除
collection.DeleteOne(i => i.Id == "365");

Because it supports Linq, it is very convenient to use. Of course, you can also use the query function of MongoDb itself.

//查询
result = collection.Find(Builders<Person>.Filter.Eq(i=>i.Name, "Jack")).ToList();

//更新
collection.ReplaceOne(Builders<Person>.Filter.Eq(i => i.Id, "365"), person);
                                                                                    
// Update some fields 
collection.UpdateOne(Builders<Person>.Filter.Eq(i => i.Id, " 365 " ),
    Builders<Person>.Update.Set(i => i.Age, 30));
                                                                                                                            
//删除
collection.DeleteOne(Builders<Person>.Filter.Eq(i => i.Id, "365"));

 

Even, if you can use MongDB commands, you can also use Mongo commands directly, which is more concise.

//查询
result = collection.Find("{ Name: 'Jack' }").ToList();
                                                    
//更新
collection.UpdateOne("{Name: 'Jack' }", "{$set:{'Age':'37'}}");
                                                    
//删除
collection.DeleteOne("{Name: 'Jack' }");

这种方式类似Sql,非常简洁,但是失去了类型检查,至于如何使用,则需要看具体场合了。

 Reference documentation:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324400837&siteId=291194637