2010-03-16 106 views
10

使用MongoDB C#驱动程序(http://github.com/samus/mongodb-csharp),似乎我无法通过ObjectId获取数据。下面是我使用的命令:MongoDB C#驱动程序无法通过对象ID查找?

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查找?

谢谢..

回答

11

它确实支持通过对象ID进行抓取。你的id变量应该是一个Oid。这是正确的类型吗?

下面是一个完整的程序,将

  • 连接到蒙戈
  • 插入
  • 文档提取文档背面使用其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()); 
+0

@Ant:请您详细说明一下吗? 你的意思是,这样的事情? var spec = new Document {{“Oid”,id}}; – heisthedon 2010-03-16 10:57:25

+0

你是冠军..它的工作原理:) 感谢您的帮助.. – heisthedon 2010-03-16 11:16:39

+0

这是使用官方驱动程序或规范? – 2012-01-14 16:17:49

0

变种规格=新文献{{ “_id”,ObjectId.Parse(ID)}};

var doc = mc.FindOne(spec);

+0

您能否详细说明您的答案,并添加关于您提供的解决方案的更多描述? – abarisone 2015-04-14 12:22:31