[mongo-csharp-driver] BsonId required?

163 views
Skip to first unread message

Nat

unread,
Nov 2, 2010, 12:13:58 PM11/2/10
to mongodb-user
Robert,

if a class is defined like

public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
}

it can be properly serialized to MongoDB but it cannot be deserialized
back because the returned document will have extra _id in which it
will fail the serialization. I don't think it should fail. What do you
think?

Thanks,

Robert Stam

unread,
Nov 2, 2010, 12:32:32 PM11/2/10
to mongodb-user
There are two things you can do to deserialize this class and not fail
because of the extra element:

1. Use the [BsonIgnoreExtraElements] attribute:

[BsonIgnoreExtraElements]
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
}

2. If you want to stay away from attributes on your POCOs use the
following during the initialization of your application:

BsonClassMap.RegisterClassMap<Person>(cm => {
cm.AutoMap();
cm.SetIgnoreExtraElements(true);
});

Keep in mind that RegisterClassMap can only be called once per type.

Do you think the default should be to ignore extra elements? My though
was that it was better to default on the side of safety (how do we
know it's safe to ignore extra elements?).

Robert Stam

unread,
Nov 2, 2010, 12:35:41 PM11/2/10
to mongodb-user
Of course you could always add an Id property... :-)

Seriously, often you will need to have the Id property anyway.

Nat

unread,
Nov 2, 2010, 11:44:54 PM11/2/10
to mongodb-user
sometimes you don't really want to such as if you need to give your
object model to someone else. You probably don't want to introduce a
dependency to ObjectId or Bson library.

Nat

unread,
Nov 4, 2010, 10:14:22 AM11/4/10
to mongodb-user
Interesting thing is that _id is provided by default. Even calling
find({},{x:1,y:1}) still returns _id. This means you cannot do select
your own fields you need and do FindAs<T>

Robert Stam

unread,
Nov 4, 2010, 10:22:33 AM11/4/10
to mongodb-user
The syntax in the shell to omit the _id is:

> db.test.find({}, {x:1, y:1, _id:0})

You have to specifically exclude it. It's different from regular
fields in that respect.

Nat

unread,
Nov 4, 2010, 10:31:50 AM11/4/10
to mongodb-user
awesome. Thanks!
Reply all
Reply to author
Forward
0 new messages