I have Json data whose full structure I don't know. I want to store this data in MongoDb using c# driver.
I couldn't use c# dynamic keyword as this is not supported by Mongo C# Serializer.
I worked around this by creating Bson documents based on json passed.
var bsonDocument = BsonSerializer.Deserialize<BsonDocument>(json);
testcollection.Insert(bsonDocument,SafeMode.True);
I want to use linq to query such documents without using a type so that I can get back a list of BsonDocuments matching a criteria.
I was thinking a of creating ExpressionTree visitor to convert linq ->javascript. I see that in mongo c# driver we can create query using javascript
var script = new BsonJavaScript(stringJs);
var mongoQuery = Query.Where(script)
Is there any other way I can do this.
Thanks for your suggestion.
I used the follwoing approach .
1. Get the MongoQueryable<T> for a collection
var provider = new MongoQueryProvider(collection);
return new MongoQueryable<T>(provider);
2. Create a linq query using the MongoQueryable<T>
3. use ((MongoQueryable<T>)query).GetMongoQuery() to convert a linq query to a valid monogo query.
4. Executing the mongo queries on collection returns valid BSON document.
Best Regards,
Sid
var query = from dynamic p in collection
where p.Id== id
select p;
To solve this I was using mongo query builder to write my queries which worked but is a little bit cumbersome.
Now my approach is to get the IQueryable using
var queryable = new MongoQueryProvider(collection);
return new MongoQueryable<T>(provider);
Create linq query
var query = from p in queryable
where p.Id== Id
select p;
To Execute this query I convert this query into mongo query
var mongoquery = ((MongoQueryable<T>)query).GetMongoQuery();
Then I can get the cursor using get cursor method
private static MongoCursor GetCursor(MongoCollection collection, IMongoQuery query)
{
var cursor = MongoCursor.Create(typeof(BsonDocument), collection, query);
return cursor;
}
Now I can itierate the cursor
var result = cursor.Cast<BsonDocument>().ToList();