繁体   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