我是新來的MongoDB所以這可能是一個幼稚的問題,但我還沒有被周圍的Googling發現任何相關/最新的信息:我試圖使用MongoDB的C#驅動程序(版本2.2.4),以構成一個基於LINQ查詢,一次一個塊,從接收到的filter
POCO對象,如下所示:現在MongoDB的C# - LINQ包含對一個字符串數組拋出ArgumentException的
IQueryable<BsonDocument> parts = collection.AsQueryable();
if (filter.Name != null)
parts = parts.Where(d => d["Name"].Equals(filter.Name));
// ... etc; I'll then call ToList() to get results ...
,我filter
性質之一是一個字符串數組,這意味着我應該匹配其字段爲Vendor
(MongoDB文檔中的字符串屬性)的任何文檔與陣列中的任何字符串相同(如MongoDB本機$in
:https://docs.mongodb.com/manual/reference/operator/query/in/) 。
爲此,我與Contains
嘗試(對於1大小的數組的特殊情況下只是一個優化):
if (filter.Vendors != null && filter.Vendors.Length > 0)
{
parts = filter.Vendors.Length == 1
? parts.Where(d => d["Vendor"].Equals(filter.Vendors[0]))
: parts.Where(d => filter.Vendors.Contains(d["Vendor"].AsString));
}
此編譯,但將引發ArgumentException
「型表達的「MongoDB的。 Bson.BsonValue'不能用於方法'Boolean Contains [String](System.Collections.Generic.IEnumerable`1 [System.String],System.String)'「的類型'System.String'的參數。
看着http://mongodb.github.io/mongo-csharp-driver/2.2/reference/driver/crud/linq/,沒有關於Contains
或$in
;然而,從https://jira.mongodb.org/browse/CSHARP-462
看來,司機現在應該能夠處理該方法。
順便說一句,同樣的情況,如果我稍微改變代碼:不涉及Contains
在所有
parts.Where(d => filter.Vendors.Any(s=> d["Vendor"].Equals(s)));
。有關無法使用BsonValue
爲string
異常消息抱怨,然而這BsonValue
是權利string
。任何人都可以提出解決方案
感謝那些做到了!在我的情況我必須保持現有的API(即我不能修改過濾器對象模型),所以我只是創建類型列表,與filter.ItemIds.Select(S => BsonString.Create的字符串值的包裝( s))ToList(),然後按照你的建議應用過濾器。 –
Naftis