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!

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

2 Answers 2

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"));
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.