Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve a subset of fields using the C# MongoDB driver?

Tags:

c#

mongodb

I've searched the world over and can't seem to find the answer to this.

How do I do this in C#:

// retrieve ssn field for documents where last_name == 'Smith':
db.users.find({last_name: 'Smith'}, {'ssn': 1});

Thanks!

like image 208
Christopher Davies Avatar asked Jun 30 '11 19:06

Christopher Davies


2 Answers

To include:

.SetFields(Fields.Include("first_name", "last_name"));

To exclude fields:

.SetFields(Fields.Exclude("SSN","Salary"));

To do both:

.SetFields(Fields.Include("first_name", "last_name").Exclude("SSN","Salary"));
like image 127
kheya Avatar answered Nov 17 '22 20:11

kheya


Note that you can now use a (type/refactoring)-safe version:

usersCollection.FindAllAs<User>()
               .SetFields(Fields<User>.Include(user => user.FirstName,
                                               user => user.LastName)
                                      .Exclude(user => user.SSN)
               .ToArray();
like image 26
Pragmateek Avatar answered Nov 17 '22 19:11

Pragmateek