[英]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
}
]
}
我需要選擇所有參數,這些對象中的參數集合中的任何參數都適用於以下條件:
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 ...
據我所知,此查詢不會獲取滿足您條件的參數,而是獲取整個文檔本身。 那是什么意思嗎? 要僅選擇一組子文檔,必須使用組。
話雖如此,您可以像這樣直接基於Mongo查詢創建過濾器
BsonDocument filter = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>("{ Parameters: { $elemMatch: { Key: 104, $and: [{Value: { $gte: 8 }}, {Value: { $lte: 10 }}] } } })")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.