mongodb c#如何使用BSON文档

时间:2013-08-05 22:20:52

标签: c# mongodb bson

我花了很多时间寻找答案...... 这在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)"
}

访问“name”和“updated”没有问题,但无法弄清楚如何访问“fields”数组。

到目前为止

代码:

{
   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,而不是任何子文档值。

提前感谢您的任何帮助! 在我读完读数之后,我也想要写数据......

1 个答案:

答案 0 :(得分:37)

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

 // 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属性将字段值强制转换为特定类型,如上所示。