【问题标题】:How to use MongoDB's Query and QueryBuilder in c# foreach loop?如何在 c# foreach 循环中使用 MongoDB 查询和查询生成器?
【发布时间】:2013-03-03 18:28:13
【问题描述】:

我正在尝试查询我的收藏,但我不确定如何“追加”到Query.And()

这是我创建 Item 文档的域模型:

public class Item
{
    public ObjectId Id { get; set; }
    public string ItemTypeTemplate { get; set; }
    public string UsernameOwner { get; set; }

    public IList<ItemAttribute> Attributes { get; set; }
}

IList&lt;ItemAttribute&gt; 集合会根据 ItemTypeTemplate 的变化而变化(某个项目属性的预定列表的某种查找键)

这是Item 文档的示例:

{
    "_id" : ObjectId("5130f9a677e23b11503fee72"),
    "ItemTypeTemplate" : "Tablet Screens", 
         //can be other types like "Batteries", etc.
         //which would change the attributes list and values
    "UsernameOwner" : "user032186511",
     "Attributes" : [{
         "AttributeName" : "Screen Size",
         "AttributeValue" : "10.1"
     }, {
         "AttributeName" : "Pixel Density",
         "AttributeValue" : "340"
     }]
}

问题

鉴于IList&lt;ItemAttribute&gt; 的“动态”性质,我无法手动指定AttributeNameAttributeValue 的附加查询条件,因此我想到了使用循环来构建查询:

QueryBuilder<Item> qbAttributes = new QueryBuilder<Item>();

foreach (var attribute in item.Attributes)
{
    qbAttributes.And(
        Query.EQ("Attributes.AttributeName", attribute.AttributeName),
        Query.EQ("Attributes.AttributeValue", attribute.AttributeValue),
    );
}

var query = Query.And(
    Query.EQ("TemplateId", item.TemplateId),
    Query.NE("UsernameOwner", item.UsernameOwner)
);

return DBContext.GetCollection<Item>("Items").Find(query).AsQueryable();

如何将qbAttributes“附加”到query?我尝试了qbAttributes.And(query);,但.Find(query) 错误,参数无效。

我需要一些类似的东西:

var query = Query.And(
    Query.EQ("ItemTypeTemplate", item.ItemTypeTemplate),       //Tablet Screens
    Query.NE("UsernameOwner", item.UsernameOwner)              //current user

    // this part is generated by the loop

    Query.EQ("Attributes.AttributeName", "Screen Size"),
    Query.EQ("Attributes.AttributeValue", "10.1"),

    Query.EQ("Attributes.AttributeName", "Pixel Density"),
    Query.EQ("Attributes.AttributeValue", "340")
);

【问题讨论】:

    标签: c# mongodb mongodb-.net-driver


    【解决方案1】:

    虽然未经测试(因为我没有与您类似的场景来测试),但您应该能够像这样将各种and 条件添加到集合(实现IEnumerable)中,然后将其传递给QueryBuilder 实例的And 方法:

    var andList = new List<IMongoQuery>();
    
    foreach (var attribute in item.Attributes)
    {
        andList.Add(Query.EQ("Attributes.AttributeName", attribute.AttributeName));
        andList.Add(Query.EQ("Attributes.AttributeValue", attribute.AttributeValue));
    }
    
    andList.Add(Query.EQ("TemplateId", item.TemplateId));
    andList.Add(Query.NE("UsernameOwner", item.UsernameOwner));
    
    var query = new QueryBuilder<Item>();
    query.And(andList);
    // do something with query ...
    

    上面的代码应该等同于在所有指定条件下执行$and

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 2014-05-14
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多