Recently I started using MongoDB.I have to read specific fields(columns) from mongodb using mongodb C# driver.That means i have to read specific fields no matter whatever the values.i need to just specify the fields.I have unstructured data in my db.so i have no model class in my project.
I read Collection using Getcollection<> from the C# library.then after i stucked with this task.
How can i achieve?
There are a few ways you can achieve this depending on if your unstructured data is known at compile time or runtime.
For compile type, you can model your projection of the data and use the projection builder to specify how your projection should work
var collection = database.GetCollection<Customer>("customers");
var document = new Customer(){Name = "Joe Bloggs", Age = 30, Address = "York"};
collection.InsertOne(document);
var projection = Builders<Customer>
.Projection
.Include(x => x.Id).Include(x => x.Age);
var customerProjection = await collection.Find(x => true)
.Project<CustomerProjection>(projection)
.FirstAsync();
Above we specified the return type as the generic argument but if we omit this then we'll be returned a BsonDocument
which can be useful depending on your usage
var bsonDocument = await collection.Find(x => true)
.Project(projection)
.FirstAsync();
We can also achieve the same result by using linq expression:
var projection = await collection.Find(x => true)
.Project(x => new {x.Id, x.Age}).FirstAsync();
This will result in returning an annomous type with an Id and Age.
However if we don't know the data at compile time and are basing the fields of magic strings at runtime then you'll need to pass in BsonDocument
to the GetCollection
method:
var collection = database.GetCollection<BsonDocument>("customers");
You'll now be able to do both of the above methods to project the bson document but it will be on a per field basis.
However, I'd advise trying to use the Project builders as it will make your life a little easier:
var projectionDefinition = Builders<BsonDocument>.Projection
.Include("age")
.Exclude("_id");
var projection = await collection.Find(x => true)
.Project(projectionDefinition)
.FirstAsync();