使用Mongodb C#在列表数组中查找值

时间:2018-12-26 23:57:11

标签: c# mongodb

我有以下JSON数据。我想搜索一个EmpId并返回一条记录。

我正在使用下面的代码,但是它返回所有EmpId。

我想搜索一个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#代码:查找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.
              }

}

2 个答案:

答案 0 :(得分:0)

我认为您正用下面的代码行覆盖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

尝试删除第二行。

希望有帮助!

答案 1 :(得分:0)

我找到了解决方案,我写了如下过滤查询,它工作正常。

 var Queryfilter = Builders<EmpInfoData>.Filter.And(
                 Builders<EmpInfoData>.Filter.ElemMatch(x => x.Employee, r => r.EmpId == rid.EmpId));