Mongodb常規操做【一】

Mongodb是一種比較常見的NOSQL數據庫,數據庫排名第四,今天介紹一下Net Core 下,常規操做。mongodb

首先下C# 版的驅動程序 「MongoDB.Driver」,相關依賴包自行引用進來。 過於細節的基礎知識就不講了,直接就奔主題了數據庫

using MongoDB.Driver; //命名空間           
MongoClient client = new MongoClient("mongodb://192.168.99.5");
IMongoDatabase dbBase = client.GetDatabase("School");

 Mongodb有一個特性,你能夠不用先建數據庫和集合,數據庫會自行檢查,若是沒有就新建。數組

IMongoCollection<> collection = dbBase.GetCollection<>("Class"); //獲取集合
GetCollection是一個泛型方法,你能夠輸入BsonDocument,或者實體,Mongodb驅動程序會自動幫你序列化
IMongoCollection<BsonDocument> collection = dbBase.GetCollection<BsonDocument>("Class");
  public class Class
    {
        public BsonObjectId Id { set; get; }

        public string ClassName { set; get; }

        public List<Student> StudentItems { set; get; }
    }

    public class Student
    {
        public string Name { set; get; }

        public int Age { set; get; }

        public string Sex { set; get; }
    }

  IMongoCollection<Class> collection = dbBase.GetCollection<Class>("Class");

 若是你使用BsonDocument,那麼你會得麼一個BsonDocument對象,Mongodb驅動程序內置了序列化方法,方便將BsonDocument轉換成實體對象。異步

using MongoDB.Bson.Serialization;//命名空間
var schoolClass = BsonSerializer.Deserialize<Class>(new BsonDocument());

Mongodb驅動程序支持Linq 語法,你能夠藉此寫出優雅語句。ui

var schoolClass = collection.Find(n => n.ClassName == "一年級").FirstOrDefault();
var schoolClass2 = collection.AsQueryable<Class>().Where(n => n.ClassName == "一年級").FirstOrDefault();
var schoolClass3 = collection.Find(new BsonDocument("ClassName", "一年級")).FirstOrDefault();

Mongodb驅動程序還支持異步方法,根據命名約定,不少方法相應的Async結尾的,都是異步方法。spa

var schoolClass = await collection.Find(n => n.ClassName == "一年級").FirstOrDefaultAsync();
var schoolClass2 = await  collection.AsQueryable<Class>().Where(n => n.ClassName == "一年級").FirstOrDefaultAsync();
var schoolClass3 = await  collection.Find(new BsonDocument("ClassName", "一年級")).FirstOrDefaultAsync();

 基本介紹完畢,下面進入增刪更改的操做方法。code

---------------------------增長---------------------------------對象

 
 
IMongoCollection<Class> collection = dbBase.GetCollection<Class>("Class");
//寫入單個
collection.InsertOne(new Class
{
    ClassName = "二年級",
    StudentItems = new List<Student>
    {
        new Student{Age=10,Name="李明",Sex="" },
        new Student{Age=12,Name="小紅",Sex="" }
    }
});
//批量寫入
collection.InsertMany(new List<Class>
{
    new Class
    {
        ClassName = "二年級",
        StudentItems = new List<Student>
        {
            new Student{Age=10,Name="李明",Sex="" },
            new Student{Age=12,Name="小紅",Sex="" }
        }
    }
});

 

IMongoCollection<BsonDocument> collection = dbBase.GetCollection<BsonDocument>("Class");
//寫入單個
collection.InsertOne(new BsonDocument {
    {"ClassName","二年級" },
    {"StudentItems",new BsonArray{
            new BsonDocument { { "Age", 10 },{ "Name", "李明" },{ "Sex", "" } }
        }
    }
});
//批量寫入
collection.InsertMany(new List<BsonDocument>
{
    new BsonDocument {
    {"ClassName","二年級" },
    {"StudentItems",new BsonArray{
            new BsonDocument { { "Age", 10 },{ "Name", "李明" },{ "Sex", "" } }
        }
    } },
    new BsonDocument {
    {"ClassName","二年級" },
    {"StudentItems",new BsonArray{
            new BsonDocument { { "Age", 10 },{ "Name", "李明" },{ "Sex", "" } }
        }
    } }
});

 

不過,使用C#語言,我仍是儘可能推薦使用實體來添加,可讀性,維護性也強。也有缺點,JSON結構若是使用實體話,類庫較大,慶幸的Mongodb驅動程序能夠幫你序列化。blog

BsonDocument結構雖然符合JSON,用起來卻很痛苦,不過也減小類庫的數量。get

---------------------------刪除---------------------------------

IMongoCollection<Class> collection = dbBase.GetCollection<Class>("Class");
//刪除單個
collection.DeleteOne(n => n.ClassName == "二年級");//使用拉姆達表達式
collection.DeleteOne(new BsonDocument("ClassName", "二年級"));//使用BsonDocument
var filter = Builders<Class>.Filter.Eq("_id", new BsonObjectId("5a545e9381a98c3ab46c9cb9"));
collection.DeleteOne(filter);//使用Builders,
//批量刪除
collection.DeleteMany(n => n.ClassName == "二年級");
collection.DeleteMany(new BsonDocument("ClassName", "二年級"));
collection.DeleteMany(filter);
//刪除並返回
collection.FindOneAndDelete(n => n.ClassName == "三年級");

 

IMongoCollection<BsonDocument> collection = dbBase.GetCollection<BsonDocument>("Class");
//刪除單個
collection.DeleteOne(new BsonDocument("ClassName", "二年級"));//使用BsonDocument
var filter = Builders<BsonDocument>.Filter.Eq("_id", new BsonObjectId("5a545e9381a98c3ab46c9cb9"));
collection.DeleteOne(filter);//使用Builders,
//批量刪除
collection.DeleteMany(new BsonDocument("ClassName", "二年級"));
collection.DeleteMany(filter);
//刪除並返回
collection.FindOneAndDelete(new BsonDocument("ClassName", "二年級"));

 

使用BsonDocument,就不能使用酷酷的拉姆達表達式了,其它的差很少。

---------------------------更改---------------------------------

IMongoCollection<Class> collection = dbBase.GetCollection<Class>("Class");
//修改單個
var filter = Builders<Class>.Filter.Eq("_id", new BsonObjectId("5a545e9381a98c3ab46c9cb8"));
var update = Builders<Class>.Update.Set("ClassName", "三年級");
var update2 = Builders<Class>.Update.Set(n => n.ClassName, "三年級");

collection.UpdateOne(n => n.ClassName == "二年級", update);//使用拉姆達表達式
collection.UpdateOne(filter, update2);//使用Builders
//批量修改
collection.UpdateMany(n => n.ClassName == "二年級", update);
collection.UpdateMany(filter, update2);
//替換
var schoolClass = collection.Find(n => n.ClassName == "二年級").FirstOrDefault();
collection.ReplaceOne(n => n.ClassName == "二年級", schoolClass);

 

 使用BsonDocument 也是相應差很少,我就不貼出代碼了。

 修改數組,則大概以下

//數組增長一個
var update = Builders<Class>.Update.Push("StudentItems", new Student { Age = 18, Name = "張明", Sex = "" });
collection.UpdateOne(n => n.ClassName == "三年級", update);
//數組減小一個
var update2 = Builders<Class>.Update.Pull(n => n.StudentItems, new Student { Age = 18, Name = "張明", Sex = "" });
collection.UpdateOne(n => n.ClassName == "三年級", update2);
//數組修改一個
var update3 = Builders<Class>.Update.Set("StudentItems.$.Age", 30);
collection.UpdateOne(n => n.ClassName == "三年級" && n.StudentItems.Any(m=>m.Age==10), update3);
var update4 = Builders<Class>.Update.Set("StudentItems.$", new Student { Age = 18, Name = "張明", Sex = "" });
collection.UpdateOne(n => n.ClassName == "三年級" && n.StudentItems.Any(m => m.Age == 10), update4);

 

 示例是篩選過,不能每種寫法寫出來,讀者自行試嘗組合

---------------------------查詢---------------------------------

var shoolClass = collection.Find(n => n.ClassName == "三年級").FirstOrDefault();//使用拉姆達表達式
var shoolClassItems = collection.Find(n => n.ClassName == "三年級").ToList();
var shoolClass2 = collection.Find(new BsonDocument("ClassName", "三年級")).FirstOrDefault();
var shoolClassItems2 = collection.Find(new BsonDocument("ClassName", "三年級")).ToList();
var filter = Builders<Class>.Filter.Eq(n => n.ClassName, "三年級");//使用Builders
var shoolClass3 = collection.Find(filter).FirstOrDefault();
var shoolClassItems3 = collection.Find(filter).ToList();

 

Mongodb的基本應用,就講解完畢,筆記一下

相關文章
相關標籤/搜索