Reputation: 11
I have MongoDB collection from which I would like to query documents knowing only names of the keys.
I cannot use hardcoded base class because amount on keys will change over time in runtime. But as user I will know the names of them.
I tried doing it like that:
var collection = database.GetCollection<BsonDocument>(mongoCollectionName);
List<BsonDocument> list = (from c in collection.AsQueryable<BsonDocument>()
where c.GetElement("serial").Value == 1
select c).ToList();
but with that i get {document}.GetElement("serial").Value is not supported
So is there a way to use linq to query basic BSONs ?
Thanks !
Upvotes: 0
Views: 583
Reputation: 753
Just make the viewModel same as the properties in MongoDb. and For getting serial column whose value is 1, just do like this,
public class ViewModel {
.... model Properties goes here
}
var SerialNo = 1;
var collection = mongoDatabase.GetCollection<ViewModel>("name of your collection");
var builder = Builders<ViewModel>.Filter;
builder.Eq(x => x.serial, SerialNo );
Upvotes: 1
Reputation: 1694
Is it necessary to use LINQ? I mean it is not possible for you to do something like this?
var collection = database.GetCollection<BsonDocument>(mongoCollectionName);
List<BsonDocument> list = collection.Find(Builders<BsonDocument>.Filter.Eq("serial", 1)).ToList();
or even convert it to Dictionary.
Upvotes: 0