go through every element in a BsonDocument (c#)

3,468 views
Skip to first unread message

ruby

unread,
Dec 15, 2010, 8:34:31 PM12/15/10
to mongod...@googlegroups.com
hi,
is there some easy way to go through every element
in a BsonDocument (c#) (unknown schema)?

any need to process each element by their type like this ? :

process(BsonDocument bd)
foreach(be in bd)
if (be.BsonDocument)
process( (BsonDocument)be )
if (be.BsonDocumentArray)
...
if ...

Robert Stam

unread,
Dec 15, 2010, 11:08:21 PM12/15/10
to mongodb-user
You have two main choices for iterating over the elements in a
BsonDocument:

BsonDocument document;
foreach (BsonElement element in document) {
// process element (using element.Name and element.Value)
}

or:

foreach (BsonValue value in document.Values) {
// process value
}

The difference is in the data type of the iteration variable.

To figure out the type of each value you can do things like:

if (element.Value.IsBsonDocument) { ... }
if (value.IsBsonDocument) { ... }
if (value is BsonDocument) { ... }

switch (value.BsonType) {
case BsonType.Document: ...
case BsonType.Array: ...
etc...
}

Let me know if I didn't completely answer your question.
Reply all
Reply to author
Forward
0 new messages