[英]How to find items in a collection that nested array field contains specific string using mongodb .net driver C#?
我的收藏中有ClassRoom
文檔,每個ClassRoom
中都有一組Students
。 如何找到學生的名字或姓氏包含特定字符串的班級? 注意:我想使用過濾器構建器來實現它,而不是 Linq 也不是聚合管道。
[
{
_id: 1,
name: 'Room1',
students:
[
{
_id: 1,
firstName: 'John Junior',
lastName: 'Smith'
},
{
_id: 2,
firstName: 'Jane',
lastName: 'Jones'
}
]
},
{
_id: 2,
name: 'Room2',
students:
[
{
_id: 3,
firstName: 'Mike',
lastName: 'John'
},
{
_id: 4,
firstName: 'Kate',
lastName: 'Doe'
}
]
},
{
_id: 3,
name: 'Room3',
students:
[
{
_id: 5,
firstName: 'Johnathan',
lastName: 'Davis'
}
]
}
]
例如,如果我們得到字符串john
,查詢將返回所有教室。
您可以將 $elemMatch 與 $regex 結合使用,例如:
// Define the regex to look for
var regex = new Regex("john", RegexOptions.IgnoreCase);
// Set up the filter
var filter = Builders<Class>.Filter.ElemMatch(
x => x.Students,
Builders<Student>.Filter.Or(
Builders<Student>.Filter.Regex(x => x.FirstName, regex),
Builders<Student>.Filter.Regex(x => x.LastName, regex)
));
// Read results
var result = await (await classes.FindAsync(filter)).ToListAsync();
就性能而言,使用正則表達式並不是最佳選擇; 如果太慢,你也可以看看全文搜索。 有關詳細信息,請參閱此鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.