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?
You need to create an instance of
ObjectIdand then query using that instance, otherwise your query comparesObjectIds to string and fails to find matching documents.This should work: