我是 MongoDB 的新手,所以这可能是一个天真的问题,但我还没有通过谷歌搜索找到任何相关/最新信息:我正在尝试使用 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 native $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)'”。
查看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)));
根本不涉及包含
。异常消息提示无法将 BsonValue
用于 string
,但 BsonValue
是一个 string
。谁能提出解决方案?
最佳答案
异常消息围绕着完全拥抱 BsonValue
的想法跳舞让 mongo 处理类型而不是尝试转换为 string
.我让它可以让 Vendors 类型为 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");
关于c# - MongoDB C# - LINQ 包含针对字符串数组抛出 ArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39065424/