BsonDocument包含一个数组。当C#列表包含BsonDocument时,需要访问C#中的数组元素

时间:2014-11-24 07:24:56

标签: c# arrays mongodb

我有一个mongodb集合“users”,它以下列格式存储文档 -

{
    "_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。我可以用 -

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

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

但是如何使用与上述方法类似的方法在C#中获取名称,年龄和性别等数组元素值?

1 个答案:

答案 0 :(得分: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