Convert MongoCursor to json?

2,506 views
Skip to first unread message

Alex

unread,
Aug 23, 2011, 10:14:12 PM8/23/11
to mongodb-user
hi ! everyone
i 'm use c# Driver codeing.
how to Convert MongoCursor<BsonDocument> type to json type?

Robert Stam

unread,
Aug 24, 2011, 9:42:43 AM8/24/11
to mongodb-user
You can't convert a MongoCursor to JSON.

What you can do is read the documents returned by the MongoCursor one
by one and convert each document to JSON. Something like:

foreach (var document in cursor) {
var json = document.ToJson();
// do something with the json variable
}

Alternatively, if you want a single JSON array containing all the
documents returned by the cursor you could write:

var json = cursor.ToArray().ToJson();

Be careful calling this if the cursor returns many documents as it
will require large amounts of memory then.

Laura Dietz

unread,
Aug 24, 2011, 1:44:14 PM8/24/11
to mongod...@googlegroups.com
It is an iterator, it is not a json document.

I think you want to fall forEach on it and so something with the returned objects
cursor.forEach(function(Elem){printjson(Elem);}


Maybe I misunderstood your question. If you want to get more info on the current state of the cursor, the documentation says this:

"Auditing allocated cursors

Information on allocated cursors may be obtained using the {cursorInfo:1} command.

Reply all
Reply to author
Forward
0 new messages