23

我花了很多时间寻找答案......这在 PHP 中很容易,但我无法将它放在 C# 中(我是 C# 和 mongo 的新手......)我正在尝试迭代存储文档的所有级别。该文档如下所示:

{
    "_id": ObjectId("51f90101853bd88971ecdf27"),
    "fields": [
        {
            "ID": ObjectId("51fd09498b080ee40c00514e"),
            "NAME": "ID",
            "TYPE": "Text"
        },
        {
            "ID": ObjectId("51fd09a68b080ee40c0064db"),
            "NAME": "Title",
            "TYPE": "Text"
        },
        {
            "ID": ObjectId("51fd09b28b080ee40c004d31"),
            "NAME": "Start Date",
            "TYPE": "Date"
        },
        {
            "ID": ObjectId("51fd09c28b080ee40c007f2e"),
            "NAME": "Long Description",
            "TYPE": "Memo"
        }
    ],
    "name": "TODB",
    "updated": "Wed Jul 31 2013 08:20:17 GMT-0400 (Eastern Daylight Time)"
}

我访问“名称”和“更新”没有问题,但不知道如何访问“字段”数组。

到目前为止的代码:

{
    MongoServer mongo = MongoServer.Create();
    mongo.Connect();
    var db = mongo.GetDatabase("forms"); 
    mongo.RequestStart(db);
    var collection = db.GetCollection("forms");
    var query = new QueryDocument("name",
    "TODB"); 
    mongo.Disconnect();
}

@foreach(BsonDocument item in collection.Find(query))
{
    @item.GetElement("name").Value
    @item.GetElement("_id").Value
}

同样,我可以访问名称和 _id ,但不能访问任何子文档值。

提前感谢您的任何帮助!在我弄清楚读数后,我也将要写入数据....

4

1 回答 1

50

有几种方法,但这里有一个:

 // build some test data
 BsonArray dataFields = new BsonArray { new BsonDocument { 
     { "ID" , ObjectId.GenerateNewId()}, { "NAME", "ID"}, {"TYPE", "Text"} } };
 BsonDocument nested = new BsonDocument {
     { "name", "John Doe" },
     { "fields", dataFields },
     { "address", new BsonDocument {
             { "street", "123 Main St." },
             { "city", "Madison" },
             { "state", "WI" },
             { "zip", 53711}
         }
     }
 };
 // grab the address from the document,
 // subdocs as a BsonDocument
 var address = nested["address"].AsBsonDocument;
 Console.WriteLine(address["city"].AsString); 
 // or, jump straight to the value ...
 Console.WriteLine(nested["address"]["city"].AsString);
 // loop through the fields array
 var allFields = nested["fields"].AsBsonArray ;
 foreach (var fields in allFields)
 {
     // grab a few of the fields:
     Console.WriteLine("Name: {0}, Type: {1}", 
         fields["NAME"].AsString, fields["TYPE"].AsString);
 }

您通常可以使用字符串索引器["name-of-property"]来遍历字段和子文档字段。然后,使用AsXYZ属性将字段值转换为特定类型,如上所示。

于 2013-08-06T00:26:30.097 回答