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

MongoDB projection on missing field on Document
MongoDB faceted search
Mongodb c# InsertOne() - How to Handle exception
How to force serialization of decimal values inside dictionaries as doubles in mongodb csharp driver?
How do I use in $in operator using the 2.0 version of the C# mongodb driver?
What is the purpose of the MaxConnectionLifeTime setting
MongoDB C# driver throws timeout exception when trying to connect to replica set
Serialize Dictionary<long, VALUE> to BSON documents
Using a Regex against a simple list with `ElemMatch` in MongoDB .NET
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#)

Categories

HOME
batch-file
hyperlink
case
mysql-workbench
interface
solaris
owl-carousel
nsbundle
retrofit2
extjs4.2
accessibility
commonjs
enthought
automatic-ref-counting
gkturnbasedmatch
keytool
event-sourcing
scsi
job-scheduling
aws-sdk
enterprise-miner
symbols
googlebot
ms-access-2003
rpgle
twiml
panoramas
paragraph
record
jmockit
jett
gnat-gps
pdw-file-browser
sql-delete
parse-tree
dm-script
sessionstorage
modernizr
apns-php
trigonometry
stringtokenizer
skylink
parser-generator
xmldocument
drupal-theming
fwrite
nanoc
serde
wpas
azure-cli
ngmaterial
reachability
cudd
custom-lists
redbeard-ios
myspace
vulcanize
adafruit
dotnetnuke-7
jboss-tools
clipboard.js
cortex-m
invoke-sqlcmd
exim4
phpgrid
directdraw
dynamics-nav-2016
linklabel
grgit
morton-number
android-launcher
sony-lifelog-api
uncompress
dronekit-android
shopizer
actionfilterattribute
infosphere-spl
android-vibration
punycode
mdichild
jqmodal
unix-socket
cuba
grails-plugin-rabbitmq
authlogic
fpdi
dsym
koala
sbcl
script#
rolify
flex++
chart-director
midlet
monotouch.dialog
xcode3.2
cross-database
urlrewriter
matlab-load
filemerge
u2netdk
pylucene
xui
resharper-6.0
maven-1
object-database
eclipse-marketplace
addchild
folding
cuda.net
information-management
pnrp

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App