0

Hi I am trying to make a generic method to return a single value from the database I am not sure where to put the return result, value is returned as a BSON document.I need 1 value from it....

    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];

Thanks

user1264626
  • 87
  • 1
  • 10
  • possible duplicate of [Mongodb -- include or exclude certain elements with c# driver](http://stackoverflow.com/questions/8448179/mongodb-include-or-exclude-certain-elements-with-c-sharp-driver) – WiredPrairie Aug 18 '13 at 11:43
  • The above deals with inserts not reads – user1264626 Aug 18 '13 at 11:53
  • Also I cannot asign the class because its a global search , per specified table not predefined – user1264626 Aug 18 '13 at 12:02
  • No, the link does not deal with inserts, it's mostly about doing a MongoDb projection. `SetFields` is used to select fields. – WiredPrairie Aug 18 '13 at 12:42
  • I don't understand your comment about a "global search". There are no tables in MongoDb. – WiredPrairie Aug 18 '13 at 12:44
  • I am trying to make a method that takes a a group of variables, these varibles can be any item in the database, lets say I want to make a method that searches the user ID for the user "test" So I pass the method string key, string value, string ducument, string datatable, gettign the values from the document, next I want to search for websites in a different document, same deal I pass the required information for the next document and I get a result, I want the class to be generic, not fixed to any document, I want to pass the key:value and get back the search key I require, – user1264626 Aug 18 '13 at 12:50

1 Answers1

1

I think you need oneDocument[key] and not oneDocument[value]. Just tested this code:

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"];

It returns "Red" allright

Roman Pekar
  • 107,110
  • 28
  • 195
  • 197