Dame Lyngdoh
Dame Lyngdoh

Reputation: 352

Get distinct nested document values from a collection in MongoDB using C#

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)

Upvotes: 0

Views: 2857

Answers (1)

s7vr
s7vr

Reputation: 75954

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>();

Upvotes: 2

Related Questions