mongodb-csharp


Include/Exclude fields in query with MongoDB C# driver 2.4


We have a collection contains documents in the server. Each document is like:
{ _id: "...", Prop1: "", Prop2: "", Prop3: "", LargeField: "", ... }
There're many other fields but they're not required by the client.
I want to load documents as MyDoc class whose definition is:
public class MyDoc {
public string Id { get; set; }
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
public string LargeField { get; set; }
}
I've tried:
var client = new MongoClient(uri);
var database = client.GetDatabase("MyDatabase");
var collection = database.GetCollection<MyDocs>("MyDocs");
var allDocs = collection.Find().ToList();
Then it will load all the fields for each document, so I have to put [BsonIgnoreExtraElements] on MyDoc. The issue here is that the document is large but I only needs a limit subset of fields. Is it possible to let the driver know I only need the fields defined in the class?
If not, is it possible to exclude some of the fields like the LargeField to make the result set smaller? I've tried:
var fieldsBuilder = Builders<MyDoc>.Projection;
var fields = fieldsBuilder.Exclude(d => d.LargeField);
var allDocs = collection.Find().Project(fields).ToList();
But now allDocs becomes BsonDocument list instead of the MyDoc list. How to query MyDoc with projection?
Can someone help? It's rather simple in legacy MongoDB driver but I don't know how to do it in the new driver. Thanks.
I had a similar issue, I believe you need to specify the generic type, for some reason Project automatically assumes BsonDocument. This should fix it from BsonDocument to your class.
Change:
var allDocs = collection.Find().Project(fields).ToList();
To:
var allDocs = collection.Find<MyDoc>().Project<MyDoc>(fields).ToList();
As for how to include only certain fields, this can be done just as you are doing it with builder (using Include) or with a string in json form like:
var allDocs = collection.Find<MyDoc>().Project<MyDoc>("{Prop1: 1, Prop2: 1}").ToList();
I would highly recommend checking out projection on this guy's post:
https://www.codementor.io/pmbanugo/working-with-mongodb-in-net-part-3-skip-sort-limit-and-projections-oqfwncyka
From this article:
This brings us to another difference: with a projection definition, it implicitly converts the document type from Student to BsonDocument, so what we get back is a fluent object that, in result, will be a BsonDocument (even though what we're working with is the Student type). If we want to work with Student, we have to indicate that we still want to keep the type to Student.

Related Links

projection wont work in mongodb c# driver
BsonClassMapSerializer already registered for AbstractClassSerializer
MongoDb C# Driver 2.0 Coalesce (or equivalent)?
MongoDB dynamic update of collection when changes occurs in another collection
MongoDB C# 2.0 TimeoutException
MongoDB C# 2.0 upgrade
Searching a MongoDB collection from the end (c#)
Handle extra elements outside of deserialized class
ASP.NET 5 with MongoDB
Store same fields twice during serialization
BsonDefaultValue set to empty list
Don't overwrite extra fields when serializing BSON?
MongoDB C# - how to save arbitrary JSON document as dynamic type?
mondodb linq query fails - is it mongodb driver or linq
New (2.6) $cond Aggregation Framework with c#?
C# mongod- insert fails with “unable to connect to server, attempted to read past the stream”

Categories

HOME
grok
kentico
turing-machines
paraview
fuelux
rdbms
angular-formly
rsa
apache-spark-mllib
solaris
spring-data-redis
permissions
zip
pearson-correlation
special-characters
bing-maps
arangodb
augeas
fhir
zerobrane
package-managers
intershop
red5
charles
spring-async
pimcore
exploit
displaytag
firebase-analytics
wcag
carrierwave
failover
sqlpackage
boost-asio
xbox
erb
instantiation
keras-layer
arduino-ide
salesforce-communities
imagenet
tex
css-position
google-data-api
hackintosh
ogc
watchface
angular-http
photos
flask-login
vaadin-elements
pom.xml
jboss-4.2.x
opennms
convex-optimization
x-ray
video-conferencing
edit
otp
javafx-css
vcloud-director-rest-api
stax
builtins
windows-azure-queues
gogs
kango-framework
deep
angular-ui-typeahead
data-protection
hadoop-partitioning
lz77
cortex-m
database-relations
libav
nio2
realsense
blitline
concurrentmodification
assertion
file-move
forwarding
graphics2d
cwrsync
bufferedinputstream
j-security-check
rapidsvn
browserify-shim
big-ip
cocos3d
cbind
ignite-ui
ios8-extension
dot42
vbe
onmousemove
web-farm
user-tracking
screen-size
rmdir
silent
folding
blender-2.49
purepdf
leader

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App