我有一个与C#下面的对象相似的对象。我想找到匹配的人对象,其中包含与提供的type
匹配的项目,并且该项目的sourceId
也出现在提供的sourceIds
的数组中:
Person: {
id: 1,
items: [
{
type: "one",
sourceId: 2
},
{
type: "two"
sourceId: 3
}
]
}
到目前为止,我已经提出了这个:
var filter = Builders<Person>.Filter.In(p => p.items.Where(i => i.type == "one").FirstOrDefault().sourceId, providedIds);
var results = PersonCollection.FindAsync(filter);
当我跑步时,出现此错误:
无法确定p的序列化信息=>p.items.Where(i =>(i.type ==“ one”))。FirstOrDefault()。sourceId
[据我所知,似乎Mongo驱动程序不理解FirstOrDefault
(也许也不知道在哪里)。我如何完成此查询?
MongoDB .NET驱动程序无法解释您的过滤器并将其转换为MongoDB查询语言。
您必须改用$elemMatch,过滤器可能如下所示:
{ "items" : { "$elemMatch" : { "type" : "one", "sourceId" : { "$in" : [1, 2, 3] } } } }
C#版本:
var filter = Builders<Person>.Filter.ElemMatch(f => f.items,
item => item.type == "one" && providedIds.Contains(item.sourceId));