[英]MongoDB C# - LINQ Contains against a string array throws ArgumentException
我是MongoDB的新手,所以這可能是一個天真的問題,但我沒有通過Google搜索找到任何相關/最新信息:我正在嘗試使用MongoDB C#驅動程序(版本2.2.4)來編寫LINQ-基於查詢,一次一件,來自收到的filter
POCO對象,如下所示:
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'的表達式不能用於'System.String'類型的參數'Boolean Contains [String](System.Collections.Generic.IEnumerable`1 [ 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
看來,驅動程序現在應該能夠處理該方法了。
順便說一句,如果我稍微將代碼更改為:
parts.Where(d => filter.Vendors.Any(s=> d["Vendor"].Equals(s)));
這根本不Contains
任何東西。 異常消息抱怨無法使用BsonValue
作為string
,但BsonValue
是正確的string
。 有人可以提出解決方案嗎?
異常消息圍繞着完全擁抱BsonValue
以讓mongo處理類型而不是嘗試BsonValue
轉換為string
的想法。 我讓它的供應商的類型為List<BsonValue>
。
class Filter
{
public List<BsonValue> Vendors { get; set; }
}
...
var list = parts.Where(d => filter.Vendors.Contains(d["Vendor"]));
foreach (var document in list)
{
Console.WriteLine(document["Name"]);
}
另一種方法是將文檔映射到C#類,而不是使用BsonDocument作為集合類型。
class MyDocument
{
public ObjectId Id { get; set; }
public string Name { get; set; }
public string Vendor { get; set; }
}
...
var collection = db.GetCollection <MyDocument> ("parts");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.