Search code examples
c#mongodbmongodb-.net-driver

Convert a BsonDocument into a String


I have a query that needs to return a product and all its information by its "_id" but when I print the results I get the cursor and not the values in the MongoDB collection?

var query_id = dbCollection.Find(Query.EQ("_id", "50ed4ea05baffd13a44d0154"));
return query_id.ToString();

The result is

MongoDB.Driver.MongoCursor`1[MongoDB.Bson.BsonDocument]

EDIT I have tried the .ToJson() method but that only returns []

var query_id = dbCollection.Find(Query.EQ("_id", "50ed4ea05baffd13a44d0154"));
var r = query_id.ToJson();

EDIT Here is the Code, its a basic Windows Form App that I am doing basic tests with:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string connectionString = "mongodb://127.0.0.1";
        var server = MongoServer.Create(connectionString);

        if (server.State == MongoServerState.Disconnected)
        {
            server.Connect();
            label1.Text = ("Server is connected to: " + connectionString);
            button1.Enabled = false;
        }
        else
        {
            label1.Text = ("Server Error Check DB location");
        }

        var conn = server.GetDatabase("Acord");

        var dbCollection = conn.GetCollection("Mappings");

        var query = dbCollection.FindAll();
        //textBox2.Text = query.ToList().ToJson();

        var query_first = query.First();
        //textBox2.Text = cursorResult.ToString(); 

        var query_id = Query.EQ("_id", "1");//What ID do I put in here? This is were the error is now!
        var entity = dbCollection.FindOne(query_id);
        textBox2.Text = entity.ToString();
    }
}

Here is the error I get:

An unhandled exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication1.exe

I am clearly missing something here?


Solution

  • As you've noticed, Find() returns a cursor, which could be used to traverse the query results one-by-one. But you need only a single returned item, so use FindOne() - it will return you an item instead of a cursor.

    You should also use the correct query. E.g. By-Default MongoDB uses internal 12-bytes ObjectID, so Query.EQ("_id", "1") is simply wrong. If you are not sure about the query, call FindOne() without any arguments.

    I would recommend you trying the online MongoDB shell (at http://mongodb.org) which contains an interactive MongoDB tutorial.