0

This question involves getting distinct values of a nested document in Mongo DB using C#. I have a collection of documents, each document having the structure:

{
   key1: value1,
   key2: value2,
   key3: {
      nestedKey1: nestedValue1,
      nestedKey1: nestedValue1
   }
}

I need to query a list of distinct nestedKey1 values based on the value of key1. I can do this (using a shell in Robomongo) by using the command:

db.runCommand({distinct:'collection_name', key:'key3.nestedKey1', query: {key1: 'some_value'}})

But how do I achieve this in C# (tutorial here)

Dame Lyngdoh
  • 312
  • 4
  • 18
  • 1
    Possible duplicate of [C# MongoDB Distinct Query Syntax](https://stackoverflow.com/questions/35725113/c-sharp-mongodb-distinct-query-syntax) – s7vr Jun 30 '17 at 16:58
  • @Veeram How do I specify the key key3.nestedKey1 in this case? and not to forget the filter which has to be key1: 'some_value' – Dame Lyngdoh Jun 30 '17 at 17:03

1 Answers1

2

You can try the below distinct query.

IMongoClient mongo = new MongoClient();
IMongoDatabase db = mongo.GetDatabase("databasename");
IMongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("collectionname");

BsonDocument filter = new BsonDocument("key1", "some_value");
IList<BsonDocument> distinct = collection.Distinct<BsonDocument>("key3.nestedKey1", filter).ToList<BsonDocument>();

Filter Builder Variant

var builder = Builders<YourClass>.Filter;
var filter = builder.Eq(item => item.key1, "some_value");
IList<string> distinct = collection.Distinct<string>("key3.nestedKey1", filter).ToList<string>();

Field Builder Variant

var builder = Builders<YourClass>.Filter;
var filter = builder.Eq(item => item.key1, "some_value");
FieldDefinition<YourClass, string> field = "key3.nestedKey1";
IList<string> distinct = collection.Distinct<string>(field", filter).ToList<string>();
s7vr
  • 73,656
  • 11
  • 106
  • 127