Search code examples
c#.netmongodbmongodb-.net-driver

Query MongoDB Using 'ObjectId'


I have inserted documents into MongoDB without an id. And I want to retrieve them by searching through their MongoDB ObjectId, that has been assigned in default.

Here is my attempt-

var query_id = Query.EQ("_id", "50ed4e7d5baffd13a44d0153");
var entity = dbCollection.FindOne(query_id);
return entity.ToString();

And I get following error-

A first chance exception of type 'System.NullReferenceException' occurred

What is the problem?


Solution

  • You need to create an instance of ObjectId and then query using that instance, otherwise your query compares ObjectIds to string and fails to find matching documents.

    This should work:

    var query_id = Query.EQ("_id", ObjectId.Parse("50ed4e7d5baffd13a44d0153"));
    var entity = dbCollection.FindOne(query_id);
    return entity.ToString();