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)

2
  • 1
    Possible duplicate of C# MongoDB Distinct Query Syntax Commented Jun 30, 2017 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' Commented Jun 30, 2017 at 17:03

1 Answer 1

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>();
Sign up to request clarification or add additional context in comments.

1 Comment

I found the solution. And it is very similar to your answer. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.