[英]MongoDB C# search array of objects for intersection with a list on a single field
I'm trying to search a embedded array of documents in my MongoDB documents for a match in a list of ObjectIds I have in a C# list.我正在尝试在我的 MongoDB 文档中搜索嵌入的文档数组,以查找我在 C# 列表中的 ObjectIds 列表中的匹配项。
For example If I have a class object in mongodb looking like this例如,如果我在 mongodb 中有一个 class object 看起来像这样
{
"_id": $oid,
"Name":"Politics 101",
Students: [{ "_id": 'theirid', "Name": "Ghengis Khan", "StudentId": 12345 }, ... ]
}
How can I query that list towards all classes containing a student with a student ID I have in a list with C#?如何查询包含学生 ID 的所有班级的列表?
If the embedded list was just an array of studentIds I think I could just do something like this如果嵌入式列表只是一个学生ID数组,我想我可以做这样的事情
List<int> studentIds = new List<int>() { 12345,123213,434233,234232,42312,776433 }
FilterDefinition<Class> filter = Builders<Class>.Filter.AnyIn(c => c.Students, studentIds);
var desiredClasses = database.Classes.Class.Find(filter).ToListAsync()
But what do I do when I need to match a field in an array of embedded documents?但是当我需要匹配嵌入文档数组中的字段时该怎么办?
Solution 1: Work with .ElemMatch()
解决方案 1:使用
.ElemMatch()
MongoDB query
MongoDB查询
db.collection.find({
"Students": {
$elemMatch: {
"StudentId": {
$in: [
12345,
123213,
434233,
234232,
42312,
776433
]
}
}
}
})
Demo Solution 1 @ Mongo Playground演示解决方案 1 @ Mongo Playground
MongoDB .NET Driver syntax
MongoDB .NET 驱动程序语法
FilterDefinition<Class> filter = Builders<Class>.Filter.ElemMatch(c => c.Students,
Builders<Student>.Filter.In(s => s.StudentId, studentIds));
Demo
演示
Solution 2: Work with .In()
and dot notation解决方案 2:使用
.In()
和点表示法
MongoDB query
MongoDB查询
db.collection.find({
"Students.StudentId": {
$in: [
12345,
123213,
434233,
234232,
42312,
776433
]
}
})
Demo Solution 2 @ Mongo Playground演示解决方案 2 @ Mongo Playground
MongoDB .NET Driver syntax
MongoDB .NET 驱动程序语法
FilterDefinition<Class> filter = Builders<Class>.Filter
.In($"{nameof(Class.Students)}.{nameof(Student.StudentId)}", studentIds);
Demo
演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.