2013-03-14 92 views
5

我堆疊建立在C#中的驅動程序這個MongoDB的查詢:MongoDB的:建立在C#中的驅動程序查詢

{ 
    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: Match multiple array elements 歡迎您帶標準在其解決方案中。

回答

5

下面是如何,如果你想要得到的是精確查詢:

// 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" }} 
    ] 
    } 
} 

(I」 d從來沒有見過$all的使用風格,但顯然,它聽起來像it's just not documented還沒有。)

3

雖然我可以證實,查詢你貼在我的機器上工作時,documentation of $all似乎表明,它不應該接受表達式或查詢,但只值:

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

(文檔用途如果查詢被允許,則爲<expression>compare to $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")))); 
+0

查詢與$和不是100%相當於原來的。詳情請查看我問題底部的鏈接。無論如何感謝您的回答。 – Kamarey 2013-03-17 19:19:18

相關問題