题
使用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查找?
谢谢..
解决方案
它确实支持对象ID提取。您的ID变量应该是OID。是正确的类型吗?
这是一个完整的程序
- 连接到Mongo
- 插入文档
- 使用其ID获取文档
- 打印文档的详细信息。
// 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 =新文档{{“ _id”,objectid.parse(id)}};
var doc = mc.findone(spec);
不隶属于 StackOverflow