How can I serialize a Bsondocument in JSON?

4,328 views
Skip to first unread message

sadegs

unread,
Apr 17, 2011, 10:44:10 PM4/17/11
to mongodb-user
Hello,

My webservices are using JSON strings. I've read through some posts to
use the BsonSerializer.Deserialize() to create a BsonDocument to
insert into the db. How can I Serialize the BsonDocument back to
JSON??

thanks

Here is some of my code;

MongoCollection<BsonDocument> users =
db.GetCollection<BsonDocument>("users");
BsonDocument user =
BsonSerializer.Deserialize<BsonDocument>(jsonString);
users.Insert(user);

MongoCursor<BsonDocument> all = users.FindAll();
// Ok, what can I do with this now??

var query = Query.EQ("name", "sep");
usersClass person=null;
foreach (usersClass uc in users.FindAs<usersClass>(query))
{
person = uc;
}

//this throws exception?!





[Serializable]
public class usersClass
{
public string name;
public string pass;
}

Robert Stam

unread,
Apr 17, 2011, 11:56:17 PM4/17/11
to mongodb-user
There are several things to consider. The first is that BsonDocument
is an in memory representation of a BSON document (which is almost the
same as a JSON document), and is therefore extremely flexible. Almost
any JSON document can be loaded into a BSON document and vice versa.

But once you start deserializing into a C# class the BSON document
must match the structure of the C# class almost exactly (although you
have a good bit of control over the matching using serialization
attributes or initializing class maps in code).

You don't say what exception you are getting or even what line the
exception is thrown from, but most likely it is because your document
doesn't match your C# class. At the very least your class is missing
an Id field.

To convert an object back to a JSON string you can use the ToJson
method:

BsonDocument document;
string json = document.ToJson();

or

Person person;
string json = person.ToJson();

If this doesn't answer your question please provide more information
and follow up questions.

sadegs

unread,
Apr 19, 2011, 2:54:18 PM4/19/11
to mongodb-user
Hello Robert,

I've pasted my code below... I read through the serialization tutorial
some more which was helpful.
I'm getting an exception "Id cannot be null";
users.Insert(user);

I've also tried using an Id element in my JSON input string which also
gives me an exception.

When I comment out the [BsonId] attribute and "Id" field, I get an
"Unexpected element: _id" at
user = users.FindOne();

So, if you could help me understand defining an Id element? I would
have assumed this field is used as the document id inside Mongo and
not applicable or should be exposed to application. Does every mapped
object in Bson need to have an Id property? Does it have to have the
Id namespace or just the [BsonId] attribute?

Secondly, can BSON/Mongo fill in id of document or does that need to
be done programatically with a NewGuid() type call?

thanks
-sepehr





ReadString cannot be called when BsonType is: ObjectId

class Program
{
static void Main(string[] args)
{

string input = @"{""name"":""user1"",""pass"":""pass1""}";

string mdbConfig = @"mongodb://localhost";
MongoServer mongoServer = MongoServer.Create(mdbConfig);
MongoDatabase db = mongoServer.GetDatabase(@"netopeso");

MongoCollection<usersClass> users =
db.GetCollection<usersClass>("users");
usersClass user = BsonSerializer.Deserialize<usersClass>(input);
users.Insert(user);

user = users.FindOne();
System.Console.WriteLine(user.name + " " + user.pass + " " +
user.ToJson<usersClass>());

System.Console.ReadLine();
}
}

[Serializable]
public class usersClass
{
[BsonId]
public string Id;
public string name;
public string pass;
}

Robert Stam

unread,
Apr 19, 2011, 3:03:27 PM4/19/11
to mongodb-user
Every document in MongoDB must have an Id field. That field is always
called "_id" in the database, but can be called something else in your
C# class (normally people call it "Id"). If you choose another name
different than "Id" then use the [BsonId] attribute to mark it as the
Id field.

The C# driver can generate unique values for your Id automatically,
but ONLY if the data type of your Id field is ObjectId or Guid. If you
want the data type to be string you have to assign a value to the Id
field yourself before calling Insert. The message "Id cannot be null"
means you did not assign a value to your Id field.

Once you decide on a data type for your Id field make sure all
existing documents in your collection have that data type. If you have
documents left over from earlier tests with a different data type you
will get errors. For example, "ReadString cannot be called when
BsonType is: ObjectId" probably occurred because you have existing
data in your collection where the _id field is an ObjectId and not a
string.

sadegs

unread,
Apr 19, 2011, 3:35:02 PM4/19/11
to mongodb-user
solid - i changed it to ObjectId and it's working superbly. The
serializer/deserializer is very fast as well.

i must have missed the _id field ObjectId type in the documentation...

thanks
sepehr
Reply all
Reply to author
Forward
0 new messages