0

嗨,我正在尝试创建一个通用方法来从数据库返回单个值我不确定将返回结果放在哪里,值作为 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];

谢谢

4

1 回答 1

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"它可以返回

于 2013-08-18T14:24:26.527 回答