2010-03-16 104 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