17

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!

Christopher Davies
  • 4,461
  • 2
  • 34
  • 33
  • OK, well, I was misreading an example elsewhere, but just for the record, here is the solution: users.FindAs(Query.EQ("_id", "test@foo.com")) .SetFields(Fields.Include(new string[] { "first_name", "last_name" })) – Christopher Davies Jun 30 '11 at 19:52
  • 2
    possible duplicate of [Mongodb -- include or exclude certain elements with c# driver](http://stackoverflow.com/questions/8448179/mongodb-include-or-exclude-certain-elements-with-c-sharp-driver) – i3arnon Jul 12 '14 at 13:03
  • Hm. Kind of the other way around, really. This thread is older, but they are dups of each other. – Christopher Davies Jul 13 '14 at 21:17
  • The other question has a better answer though, and that's what should count. http://meta.stackoverflow.com/a/252017/885318 – i3arnon Jul 13 '14 at 21:26

2 Answers2

16

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"));
Michael Haren
  • 105,752
  • 40
  • 168
  • 205
kheya
  • 7,546
  • 20
  • 77
  • 109
7

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();
Pragmateek
  • 13,174
  • 9
  • 74
  • 108