使用MongoDB C#驱动程序(http://github.com/samus/mongodb-csharp),似乎我无法通过ObjectId获取数据。在我正在使用的命令下面:
var spec = new Document { { "_id", id } };
var doc = mc.FindOne(spec);
我也试过这个:
var spec = new Document { { "_id", "ObjectId(\"" + id + "\")" } };
var doc = mc.FindOne(spec);
两者都没有回报。同时,如果我从mongo控制台查询它,它会返回预期的结果。
我的问题是,该驱动程序实际上是否支持ObjectId的查找?
谢谢..
答案 0 :(得分:11)
它支持按对象ID提取。你的id变量应该是Oid。它是正确的类型吗?
这是一个完整的程序
// 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());
答案 1 :(得分:0)
var spec = new Document {{" _id",ObjectId.Parse(id)}};
var doc = mc.FindOne(spec);