【问题标题】:MongoDB C# Driver Unable to Find by Object ID?MongoDB C# 驱动程序无法按对象 ID 查找?
【发布时间】:2011-01-28 01:15:24
【问题描述】:

使用 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 的查找吗?

谢谢..

【问题讨论】:

    标签: c# mongodb nosql


    【解决方案1】:
    var spec = new Document { { "_id", ObjectId.Parse(id) } }; 
    
    var doc = mc.FindOne(spec);
    

    【讨论】:

    • 能否请您详细说明您的答案,添加更多关于您提供的解决方案的描述?
    【解决方案2】:

    它确实支持按对象 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());
    

    【讨论】:

    • @Ant:你能详细说明一下吗?你的意思是,像这样的东西? var spec = new Document { { "Oid", id } };
    • 这是用官方驱动还是Norm?
    • 这是 Samus 驱动程序,当被问到问题时,它是唯一的 C# 驱动程序。它在问题本身中提到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 2013-09-01
    • 1970-01-01
    • 2011-11-19
    • 2020-04-08
    • 2023-03-13
    相关资源
    最近更新 更多