开发者

MongoDB C# Driver Unable to Find by Object ID?

Using MongoDB C# driver (http://github.com/samus/mongodb-csharp), seems that I'm unable to get the data by ObjectId. Below the command that I'm using:

var spec = new Document { { "_id", id } };
var doc = mc.FindOne(spec);

I also tried this:

var spec = new Document { { "_id", "ObjectId(\"" + id + "\")" } };
var doc = mc.FindOne(spec);

Both return nothing. Meanwhile, if I query it from the mongo console, it returns the expected result.

My question is, does that dri开发者_开发技巧ver actually support the lookup by ObjectId?

Thanks..


It does support fetching by object ID. Your id variable should be an Oid. Is it the correct type?

Here is a complete program that will

  • Connect to Mongo
  • Insert a document
  • Fetch the document back using its ID
  • Print the document's details.

// Connect to Mongo
Mongo db = new Mongo();
db.Connect();

// Insert a test document
var insertDoc = new Document { { "name", "my document" } };
db["database"]["collection"].Insert(insertDoc);

// Extract the ID from the inserted document, stripping the enclosing quotes
string idString = insertDoc["_id"].ToString().Replace("\"", "");

// Get an Oid from the ID string
Oid id = new Oid(idString);

// Create a document with the ID we want to find
var queryDoc = new Document { { "_id", id } };

// Query the db for a document with the required ID 
var resultDoc = db["database"]["collection"].FindOne(queryDoc);
db.Disconnect();

// Print the name of the document to prove it worked
Console.WriteLine(resultDoc["name"].ToString());


var spec = new Document { { "_id", ObjectId.Parse(id) } }; 

var doc = mc.FindOne(spec);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜