简体   繁体   中英

Find a value inside the List Array using Mongodb C#

I have below JSON data. I want to search a EmpId and return a single record.

I am using below code but it is returning all EmpIds.

I want search a emp Id (eg.100) and query should return a record which is EMpId equal to 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

 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:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM