[英]Find a value inside the List Array using Mongodb C#
I have below JSON data. 我下面有JSON数据。 I want to search a EmpId and return a single record.
我想搜索一个EmpId并返回一条记录。
I am using below code but it is returning all EmpIds. 我正在使用下面的代码,但它返回所有EmpId。
I want search a emp Id (eg.100) and query should return a record which is EMpId equal to 100? 我想搜索一个emp Id(例如100),查询应返回EMpId等于100的记录?
{
"EmpInfo": {
"DeptId":"C0",
"Employee":[
{
"EmpId":"100",
"isActive": true,
"Name":"smith"
},{
"EmpId":"101",
"isActive": true,
"Name":"John"
},
{
"EmpId":"102",
"isActive": true,
"Name":"Sam"
}
]
}
}
C# code: find emp Id =100 C#代码:找到emp ID = 100
var collection = _mongoDataClient.client.GetDatabase("Dbname");
var builder = Builders<EmpInfoData>.Filter;
FilterDefinition<EmpInfoData> filter;
foreach (var rid in _CatalogInfoRequest.EmpInfo.Employee)
{
filter = Builders<EmpInfoData>.Filter.ElemMatch(x => x.Employee, x => x.railId == rid.EmpId);
filter = builder.Eq("Employee.EmpId", 100);
List <EmpInfoData> dashboardContents = null;
result = collection.Find(filter).ToList();
if (result [0].Employee.Count > 0)
{
strmessage = "Update:"+result [0].children.Count; //Should return single count but returning 3 rows.
}
}
I think you are overriding your ElemMatch
filter with the line of code just below it: 我认为您正在用下面的代码行覆盖
ElemMatch
过滤器:
filter = Builders<EmpInfoData>.Filter.ElemMatch(x => x.Employee, x => x.railId == rid.EmpId);
filter = builder.Eq("Employee.EmpId", 100); // Overrides what you did in the previous line
Try removing the second line. 尝试删除第二行。
Hope it helps! 希望能帮助到你!
I got the solution, I wrote Filter Query as below, It works fine. 我得到了解决方案,我写了如下的过滤查询,它工作正常。
var Queryfilter = Builders<EmpInfoData>.Filter.And(
Builders<EmpInfoData>.Filter.ElemMatch(x => x.Employee, r => r.EmpId == rid.EmpId));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.