簡體   English   中英

BsonDocument包含一個數組。 當C#列表包含BsonDocument時,需要訪問C#中的數組元素

[英]BsonDocument contains an array. Need to access the array elements in C# when the BsonDocument is contained by a C# list

我有一個mongodb集合“用戶”,它以以下格式存儲文檔-

{
    "_id" : ObjectId("53fe7ae0ef038fee879263d5"),
    "username" : "John"
    "status" : "online",
    "profile" : [ 
        {
            "name" : "John Stuart",
            "age" : "23",
            "gender" : "male"
        }
    ]
}

我在C#.NET中使用以下功能將集合中的文檔存儲到BsonDocuments列表中-

    public static List<BsonDocument> LoadDataByWhere (string table, string whereClause)
    {
        // Here table is the collection name and whereClause is the mongodb query 

        var collection = db.GetCollection (table);
        QueryDocument whereDoc = new QueryDocument(BsonDocument.Parse(whereClause));
        var resultSet = collection.Find (whereDoc);
        List<BsonDocument> docs = resultSet.ToList();

        if (resultSet.Count() > 0) {
            foreach(BsonDocument doc in docs)
            {
                doc.Set("_id", doc.GetElement("_id").ToString().Split('=')[1]);
            }
            return docs;
        } 
        else {
            return null;
        }
    }

假設我將列表存儲在列表中。 我可以用 -

    List<string> username = new List<string>();

    foreach(BsonDocument item in list) 
    {
        username.Add(Convert.ToString(list.getElement("username").Value));
    }

但是,如何使用與上述方法類似的方法在C#中獲取名稱,年齡和性別之類的數組元素值?

我建議將Mongo文檔映射到某種形式的DTO。 Mongo支持反序列化為對象圖。

public class User
{   
    [BsonId]
    public ObjectId Id { get; set; }

    public string username { get; set; }

    public string status { get; set; }

    public List<Profile> profile { get; set; }
}


public class Profile
{

    public string name { get; set; }

    public string age { get; set; }

    public string gender { get; set; }
}

然后,您可以像這樣訪問它

const string connectionString = "mongodb://localhost";

//// Get a thread-safe client object by using a connection string
var mongoClient = new MongoClient(connectionString);

//// Get a reference to a server object from the Mongo client object
var mongoServer = mongoClient.GetServer();

//// Get a reference to the database object
//// from the Mongo server object
const string databaseName = "mydatabase";
var db = mongoServer.GetDatabase(databaseName);

//// Get a reference to the collection object from the Mongo database object
//// The collection name is the type converted to lowercase + "s"
MongoCollection<T> mongoCollection = db.GetCollection<T>(typeof(T).Name.ToLower() + "s");

因此,當您現在通過ID查詢時,它將包含配置文件的填充列表(如果存在)

使用-CSHARP驅動器

MongoDB的-與-C-深潛

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM