如何按子集合中的项目执行搜索文档

How to perform search documents by items in subcollection

我有这样的文件结构:

{
    "Name" : "Hello world",
    "Parameters" : [ 
        {
            "Key" : 104,
            "Value" : 8
        }, 
        {
            "Key" : 112,
            "Value" : 20
        }, 
        {
            "Key" : 176,
            "Value" : 2
        }, 
        {
            "Key" : 179,
            "Value" : 1
        }, 
        {
            "Key" : 180,
            "Value" : 3
        }, 
        {
            "Key" : 177,
            "Value" : 1
        }, 
        {
            "Key" : 302,
            "Value" : 1
        }, 
        {
            "Key" : 303,
            "Value" : 0
        }, 
        {
            "Key" : 178,
            "Value" : 3
        }, 
        {
            "Key" : 181,
            "Value" : 2015
        }
    ]  
}

我需要select所有对象,其中参数集合中的任何参数都适用于下一个条件:

Expression<Func<SuperObject, bool>> newPred = x => x.Parameters.Any(
    p => p.Key == id 
    && p.Value >= min 
    && p.Value <= max
)

我试过这样做:

db.SuperObjects.find({ 
    Parameters: { 
        $elemMatch: { 
            Key: 104, 
            $and: [
                {Value: { $gte: 8 }}, 
                {Value: { $lte: 10 }}
            ] 
        } 
    } 
})

它在 mongodb 中有效。但是如何用c#写这样的代码呢?

我试过了

filter = filter & builder.ElemMatch("Parameters", builder.Eq("Key", id) & builder.Gte("Value", min) & builder.Lte("Value", max));

它抛出无效的转换异常,因为试图将参数对象转换为我的 SuperObject...

据我所知,此查询不会为您提供满足条件的参数,而是整个文档本身。这是故意的吗?要 select 只有一组子文档,您必须使用组。

话虽如此,您可以像这样直接根据 Mongo 查询创建过滤器

BsonDocument filter = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>("{ Parameters: { $elemMatch: { Key: 104, $and: [{Value: { $gte: 8 }}, {Value: { $lte: 10 }}] } } })")