返回来自mongo doc的单个结果

时间:2013-08-18 11:12:57

标签: c# mongodb

您好我正在尝试使用泛型方法从数据库中返回单个值 我不确定将返回结果放在何处,将值作为BSON文档返回。我需要1个值....

    public static string SearchMongoSingleValue(string key, string value, string ducument, string datatable)
     {
         var connectionString = "mongodb://localhost";
         var client = new MongoClient(connectionString);
         var server = client.GetServer();
         var database = server.GetDatabase(datatable);
         var collection = database.GetCollection(ducument);
         var query = Query.EQ(key, value);
         var oneDocument = collection.FindOne(query);

         return oneDocument[value];

由于

1 个答案:

答案 0 :(得分:1)

我认为您需要oneDocument[key]而不是oneDocument[value]。刚刚测试了这段代码:

using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
var client = new MongoClient("mongodb://localhost");
var coll = client.GetServer().GetDatabase("local").GetCollection("test1");
var doc = new BsonDocument();
doc.Add("Name","John");
doc.Add("Color","Red");
coll.Insert(doc);
var query = Query.EQ("Name", "John");
var doc2 = coll.FindOne(query);
var value = doc2["Color"];

它返回"Red"好吧