Christopher Davies
Christopher Davies

Reputation: 4551

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

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!

Upvotes: 17

Views: 10322

Answers (2)

Pragmateek
Pragmateek

Reputation: 13374

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();

Upvotes: 7

kheya
kheya

Reputation: 7612

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"));

Upvotes: 16

Related Questions