簡體   English   中英

MongoDB:在C#驅動程序中構建查詢

[英]MongoDB: Build query in C# driver

我堆積在C#驅動程序中構建這個Mongodb查詢:

{ 
    Location: { "$within": { "$center": [ [1, 1], 5 ] } },
    Properties: {
        $all: [
            { $elemMatch: { Type: 1, Value: "a" } },
            { $elemMatch: { Type: 2, Value: "b" } }
        ]
    }
}

下一步:

var geoQuery = Query.WithinCircle("Location", x, y, radius);
var propertiesQuery = **?**;
var query = Query.And(geoQuery, propertiesQuery);

加成:

上面的查詢取自我的另一個問題: MongoDB:匹配多個數組元素歡迎您參與其解決方案。

以下是您希望獲得該確切查詢的方法:

// create the $elemMatch with Type and Value
// as we're just trying to make an expression here, 
// we'll use $elemMatch as the property name 
var qType1 = Query.EQ("$elemMatch", 
    BsonValue.Create(Query.And(Query.EQ("Type", 1),
                     Query.EQ("Value", "a"))));
// again
var qType2 = Query.EQ("$elemMatch", 
    BsonValue.Create(Query.And(Query.EQ("Type", 2), 
                     Query.EQ("Value", "b"))));
// then, put it all together, with $all connection the two queries 
// for the Properties field
var query = Query.All("Properties", 
    new List<BsonValue> { 
        BsonValue.Create(qType1), 
        BsonValue.Create(qType2)
    });

偷偷摸摸的部分是,盡管各種Query方法的許多參數都需要BsonValue而不是查詢,但您可以通過執行以下操作從Query實例創建BsonValue實例:

// very cool/handy that this works
var bv = BsonValue.Create(Query.EQ("Type", 1)); 

發送的實際查詢完全符合您的原始請求:

query = {
  "Properties": {
    "$all": [ 
        { "$elemMatch": { "Type": 1, "Value": "a" }}, 
        { "$elemMatch": { "Type": 2, "Value": "b" }}
    ]
  }
}

(我從來沒有見過這種$all使用的風格,但顯然,它聽起來還沒有記錄 。)

雖然我可以確認您發布的查詢在我的機器上運行,但$all文檔似乎表明它不應該接受表達式或查詢 ,而只是接受值:

Syntax: { field: { $all: [ <value> , <value1> ... ] }

(如果允許查詢,文檔使用<expression>$and比較 )。 因此,C#驅動程序只接受BsonValue而不是IMongoQuery的數組。

但是,以下查詢應該是等效的:

{
    $and: [
        { "Location": { "$within": { "$center": [ [1, 1], 5 ] } } },
        { "Properties" : { $elemMatch: { "Type": 1, "Value": "a" } } },
        { "Properties" : { $elemMatch: { "Type": 2, "Value": "b" } } }   
    ]
}

這轉換為C#驅動程序

var query = 
Query.And(Query.WithinCircle("Location", centerX, centerY, radius),
Query.ElemMatch("Properties", Query.And(Query.EQ("Type", 1), Query.EQ("Value", "a"))),
Query.ElemMatch("Properties", Query.And(Query.EQ("Type", 2), Query.EQ("Value", "b"))));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM