使用 C# 从 MongoDB 的集合中获取不同的嵌套文档值 [英] Get distinct nested document values from a collection in MongoDB using C#
本文介绍了使用 C# 从 MongoDB 的集合中获取不同的嵌套文档值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题涉及使用 C# 在 Mongo DB 中获取嵌套文档的不同值.我有一个文档集合,每个文档都有这样的结构:
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
}
}
我需要根据 key1 的值查询不同的 nestedKey1 值列表.我可以使用以下命令执行此操作(在 Robomongo 中使用 shell):
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'}})
但是我如何在 C# 中实现这一点(此处的教程)
But how do I achieve this in C# (tutorial here)
推荐答案
您可以尝试以下不同的查询.
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>();
过滤器构建器变体
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>();
字段构建器变体
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>();
这篇关于使用 C# 从 MongoDB 的集合中获取不同的嵌套文档值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文