萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

MongoDB 學習筆記(四):善用文件結構描述資料關係——內嵌子文件與 LINQ 實戰

核心概念:集合與文件的差異

MongoDB 集合對應關聯式資料庫的表,文件對應記錄。但集合無固定結構(Schema-free),文件可內嵌子文件或「子集合」,最終以類 BSON 格式描述。這賦予了獨特的資料管理方式。本文以 samus 驅動為例,對比基本方式與 LINQ 方式操作。

場景:會員註冊分級資料設計

某網站會員註冊分「主要資料」與「詳細資料」,初次註冊僅需填寫主要資料。詳細資訊設計為子文件儲存。

LINQ 方式實作

1. 定義資料實體類別

/// <summary> 用戶主要資料 </summary>
public class UserInfo
{
    public string UserId { get; set; }
    public string UserName { get; set; }
    public string PassWord { get; set; }
    public Detail Detail { get; set; }
}

/// <summary> 用戶詳細資料 </summary>
public class Detail
{
    public string Address { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

2. 建立業務操作類 UserBLL,完成映射配置

public class UserBLL
{
    public string connectionString = "mongodb://localhost";
    public string databaseName = "myDatabase";

    private Mongo mongo;
    private MongoDatabase mongoDatabase;
    private MongoCollection<UserInfo> mongoCollection;

    public UserBLL()
    {
        mongo = GetMongo();
        mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase;
        mongoCollection = mongoDatabase.GetCollection<UserInfo>() as MongoCollection<UserInfo>;
        mongo.Connect();
    }

    ~UserBLL() { mongo.Disconnect(); }

    /// <summary> 配置 Mongo,將 UserInfo 類映射到集合 </summary>
    private Mongo GetMongo()
    {
        var config = new MongoConfigurationBuilder();
        config.Mapping(mapping =>
        {
            mapping.DefaultProfile(profile =>
            {
                profile.SubClassesAre(t => t.IsSubclassOf(typeof(UserInfo)));
            });
            mapping.Map<UserInfo>();
        });
        config.ConnectionString(connectionString);
        return new Mongo(config.BuildConfiguration());
    }
}

3. 插入測試資料

public void InsertSomeData()
{
    mongoCollection.Save(new UserInfo { UserId = "1001", UserName = "張三", PassWord = "123456" });
    mongoCollection.Save(new UserInfo { UserId = "1002", UserName = "李四", PassWord = "123456", Detail = new Detail { Address = "湖北", Age = 20, Email = "lisi@163.com" } });
    mongoCollection.Save(new UserInfo { UserId = "1003", UserName = "王五", PassWord = "123456", Detail = new Detail { Address = "廣東", Age = 20, Email = "wangwu@163.com" } });
    mongoCollection.Save(new UserInfo { UserId = "1004", UserName = "趙六", PassWord = "123456", Detail = new Detail { Address = "湖北" } });
}

4. 查詢:找出詳細資料地址在湖北的用戶

public List<UserInfo> Select()
{
    return mongoCollection.Linq().Where(x => x.Detail.Address == "湖北").ToList();
}

小結

MongoDB 文件模型天然支援層級資料結構,配合 LINQ 強型別查詢,能以物件導向思維處理複雜關聯,大幅簡化開發。

copyright © 萬盛學電腦網 all rights reserved