1

How can I get names of all the keys in a MongoDB collection using c#. I am using mongocsharpdriver.
I am able to get all the records using

var collection1 = database1.GetCollection("Games").FindAll();

Now I need the key names to display/use it. I need key names of collection that I have fetched. e.g. If I have collection which

{ "_id" : ObjectId("c3"), "GameID" : 20, "GameName" : "COD5", "Cost" : 100}
{ "_id" : ObjectId("c4"), "GameID" : 21, "GameName" : "NFS", "Publisher" : "EA"}
{ "_id" : ObjectId("c5"), "GameID" : 22, "GameName" : "CS", "Cost" : 200}

So I should get list of keys like GameID, GameName, Cost, Publisher.

I also went through MongoDB Get names of all keys in collection but was not able to implement it, didnot understood it & got problem with mapreduce.

Community
  • 1
  • 1
G.D.
  • 177
  • 3
  • 12
  • That op is a one-liner for Java, see http://stackoverflow.com/questions/34022951/get-names-of-all-keys-name-in-collection-using-java/34023145#34023145. Maybe it's translateable. – serv-inc Dec 01 '15 at 15:05

2 Answers2

2

Inspired from the link in your question:

string map = @"function() { 
        for (var key in this) { emit(key, null); }
        }";
string reduce = @"function(key, stuff) { return null; }";
string finalize = @"function(key, value){
            return key;
        }";
MapReduceArgs args = new MapReduceArgs();
args.FinalizeFunction = new BsonJavaScript(finalize);
args.MapFunction = new BsonJavaScript(map);
args.ReduceFunction = new BsonJavaScript(reduce);
var results = collection1.MapReduce(args);
foreach (BsonValue result in results.GetResults().Select(item => item["_id"]))
{
    Console.WriteLine(result.AsString);
}
PinBack
  • 2,499
  • 12
  • 16
0

A very inefficient, but simple way to do this is

HashSet<string> keys = new HashSet<string>();
foreach (var rover in collection1.FindAll())
{
    rover.Names.ToList().ForEach(p => keys.Add(p));
}

Keep in mind that finding the set of keys, no matter how it's implemented, will always have to iterate the entire collection, so it will be terribly slow on larger collections.

It makes sense to use Map/Reduce for this problem on larger collections, because that avoids all the data transfer and deserialization overhead that is incurred by the solution I posted above, but you should generally try to avoid doing something like this at all. At least, don't do it where it's needed synchronously.

If you somehow need to know the set of all fields quickly, you're better off keeping track of the fields during writes and store the list of fields in a separate collection somewhere.

mnemosyn
  • 45,391
  • 6
  • 76
  • 82