这个问题涉及使用C#在Mongo DB中获取嵌套文档的不同值。我有一组文件,每个文件都有以下结构:
{
key1: value1,
key2: value2,
key3: {
nestedKey1: nestedValue1,
nestedKey1: nestedValue1
}
}
我需要根据 key1 的值查询不同的 nestedKey1 值列表。我可以使用以下命令执行此操作(在Robomongo中使用shell):
db.runCommand({distinct:'collection_name', key:'key3.nestedKey1', query: {key1: 'some_value'}})
但是我如何在C#(tutorial here)
中实现这一目标答案 0 :(得分:2)
您可以尝试以下不同的查询。
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>();
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>();