s.k.paul
s.k.paul

Reputation: 7311

Get only specified fields from MongoDB C#

I have the following POCO class in my app -

public class Course
{
    public String  Title { get; set; }
    public String Description { get; set; }
}

But the Course collection in mongodb has some other fields also including those. I am trying to get data as follows-

var server = MongoServer.Create(connectionString);
var db = _server.GetDatabase("dbName");
db.GetCollection("users");

var cursor = Photos.FindAs<DocType>(Query.EQ("age", 33));
cursor.SetFields(Fields.Include("a", "b"));
var items = cursor.ToList();

I have got that code from this post in stackoverflow.

But it throws an exception-

"Element '_id' does not match any field or property of class"

I don't want '_id' field in my POCO. Any help?

Upvotes: 2

Views: 849

Answers (1)

theduck
theduck

Reputation: 2617

_id is included in Fields by default.

You can exclude it by using something like:

cursor.SetFields(Fields.Exclude("_id"))

Upvotes: 5

Related Questions