2014-11-24 31 views
0

載我有一個MongoDB的集合「用戶」存儲文件的格式如下訪問C#中的數組元素 -BsonDocument包含一個數組。需要時BsonDocument由C#列表

{ 
    "_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#中的數組元素的值,如姓名,年齡和性別?

回答

1

我建議將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查詢現在它將包含輪廓的填充的列表,如果它們存在

use-csharp-driver

mongodb-with-c-deep-dive

相關問題