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

本小妞迷上赌 提交于 2019-12-24 19:17:24

问题


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)


回答1:


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


来源:https://stackoverflow.com/questions/44850951/get-distinct-nested-document-values-from-a-collection-in-mongodb-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!