mongodb c# how to work with BSON document

user2167261 picture user2167261 · Aug 6, 2013 · Viewed 66k times · Source

I've spent MANY hours looking for the answer... This is very easy in PHP but I just can't put it together in C#(I'm new to C# and mongo...) I'm trying to iterate through all levels of a stored document. The document looks like this:

{
    "_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)"
}

I have no problem accessing the "name" and "updated" but can't figure out how to access the "fields" array.

Code so far :

{
    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
}

Again, I am able to access the name and _id just not any of the sub document values.

Thanks in advance for any assistance! After I get the reading figured out, I am also going to want to write data....

Answer

WiredPrairie picture WiredPrairie · Aug 6, 2013

There are a few ways, but here's one:

 // 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);
 }

You can often use the string indexer ["name-of-property"] to walk through the fields and sub document fields. Then, using the AsXYZ properties to cast the field value to a particular type as shown above.