About c# import method of data and json convert to BsonDocument.

1,327 views
Skip to first unread message

宋维彬

unread,
Jul 22, 2011, 2:03:17 PM7/22/11
to mongod...@googlegroups.com
How to mongoexport export data, use the c# into the database? I do not find in c# related methods, as well as how to convert the json string BsonDocument?

Robert Stam

unread,
Jul 22, 2011, 2:06:30 PM7/22/11
to mongodb-user
Not sure what the first part of your question means, but you can parse
JSON into a BsonDocument using the C# driver like this:

var json = "{ a : 1 }";
var document = BsonDocument.Parse(json);
Message has been deleted

宋维彬

unread,
Jul 22, 2011, 2:12:49 PM7/22/11
to mongod...@googlegroups.com
I use mongoexport MongoDB exported data, I want to import data in ASP.net,can not use mongoimport, because the user is operating in a Web page, what better way?

Robert Stam

unread,
Jul 22, 2011, 3:08:20 PM7/22/11
to mongodb-user
OK. I understand now. The file created by mongoexport is just a bunch
of JSON documents, so there should be a way to parse them one at a
time in C# and insert them into a collection. I'll do some research
and report back.

Robert Stam

unread,
Jul 22, 2011, 4:01:46 PM7/22/11
to mongodb-user
Here's some code you can use to process the output of mongoexport
yourself in C#:

var server = MongoServer.Create("mongodb://localhost/?safe=true");
var database = server["test"];
var collection = database["test"];

using (var streamReader = new StreamReader("test.json")) {
using (var bsonReader = BsonReader.Create(streamReader)) {
while (bsonReader.CurrentBsonType !=
BsonType.EndOfDocument) {
var document = BsonDocument.ReadFrom(bsonReader);
collection.Insert(document);
}
}
}

What the code is doing is reading one BsonDocument at a time from the
BsonReader until there are no more left.

Not sure how mongoexport handles international character sets, so if
your data contains strings with international character sets you may
need to worry about character encodings.

There is one really important limitation: the entire file is loaded
into memory when the BsonReader is created. This is fine for small or
medium files, but if the file is humongous you could have problems.
Reply all
Reply to author
Forward
0 new messages