I am in a situation where I can\'t predict which fields my MongoDB document is going to have. So I can no longer create an object with an _id
field of type Bs
The driver needs to be able to find the _id field. You could create a C# class that has just two properties: Id and Values.
public class HashTableDocument
{
public ObjectId Id { get; set; }
[BsonExtraElements]
public Dictionary Values { get; set; }
}
Note that we have to use Dictionary
You could then use code like the following to insert a document:
var document = new HashTableDocument
{
Id = ObjectId.GenerateNewId(),
Values = new Dictionary
{
{ "metadata1", "asaad" },
{ "metadata2", new object[0] },
{ "metadata3", DateTime.UtcNow }
}
};
collection.Insert(document);
We can use the MongoDB shell to confirm that the inserted document has the desired form:
> db.test.find().pretty()
{
"_id" : ObjectId("518abdd4e447ad1f78f74fb1"),
"metadata1" : "asaad",
"metadata2" : [ ],
"metadata3" : ISODate("2013-05-08T21:04:20.895Z")
}
>