[CSHARP-1874] How to Update the values in Department array which is present in Employee array Created: 27/Dec/16  Updated: 03/Dec/20  Resolved: 03/Dec/20

Status: Closed
Project: C# Driver
Component/s: API, Operations
Affects Version/s: 2.4.2
Fix Version/s: None

Type: Task Priority: Major - P3
Reporter: Sunil Edupuganti Assignee: Unassigned
Resolution: Done Votes: 0
Labels: query, question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Working on Windows 10 OS



 Description   

I have Employee Class and Department Class

public class Employee
    {
        [BsonId]
        public string Id { get; set; }      
        public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Gender { get; set; }
        public List<Department.Department> Department { get; set; }
        public string Status { get; set; }
        public string ContactNo { get; set; }      
    }
 
public class Department
    {
        [BsonId]
        public string Id { get; set; }
        public int DepartmentId { get; set; }
        public string DepartmentName { get; set; }
        public string Description { get; set; }
        public string Status { get; set; }
        public DateTime CreateDateTime { get; set; }
        public DateTime ModifyDateTime { get; set; }
    }

I am able to update the fields in Employee class but I was unable to update the fields in Department Class. My question is how to update the nested array's using c#
Below is the Code:

using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDBMVC.Properties;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Web;
using System.Web.Mvc;
using Microsoft.Ajax.Utilities;
using MongoDB.Bson;
using MongoDB.Driver.Linq;
 
namespace MongoDBMVC.Employee
{
    public class EmployeeRepository : IEmployeeRepository
    {
        public MongoDatabase _MongoDB;
        public MongoCollection _MongoEmpCollection;
        public bool ServerIsDown = false;
 
        public EmployeeRepository()
        {
            var mongoClient = new MongoClient(Settings.Default.EmployeeCS);
            var server = mongoClient.GetServer();
            _MongoDB = server.GetDatabase("Employees");
            _MongoEmpCollection = _MongoDB.GetCollection("Employees");
 
            //test if server is up and running
            try
            {
                _MongoDB.Server.Ping();
                // Ping() method throws exception if not able to connect
            }
            catch (Exception ex)
            {
                ServerIsDown = true;
            }
            
        }
 
 
 
        private Employee[] _testEmployeeData = new Employee[]
        {
            new Employee()
            {
                Id = Guid.NewGuid().ToString(),
                EmployeeId = 50010,
                FirstName = "Surya",
                LastName = "Shankar",
                ContactNo = "99999999",
                Email = "Suryashankar.something.com",
                Gender = "Male",
                Department = new List<Department.Department>()
                {
                    new Department.Department()
                    {
                        Id = Guid.NewGuid().ToString(),
                        DepartmentId = 01,
                        DepartmentName = "CEO",
                        Description = "Head of the Office",
                        Status = "Active",
                        CreateDateTime = DateTime.UtcNow,
                        ModifyDateTime = DateTime.UtcNow
                    },
 
                    new Department.Department()
                    {
                        Id = Guid.NewGuid().ToString(),
                        DepartmentId = 03,
                        DepartmentName = "SAP Analyst",
                        Description = "SAP Head of the office",
                        Status = "In-Active",
                        CreateDateTime = DateTime.UtcNow,
                        ModifyDateTime = DateTime.UtcNow
                    },
                    new Department.Department()
                    {
                        Id = Guid.NewGuid().ToString(),
                        DepartmentId = 02,
                        DepartmentName = "Sr.Director",
                        Description = "CEO of the Company",
                        Status = "Active",
                        CreateDateTime = DateTime.UtcNow,
                        ModifyDateTime = DateTime.UtcNow
                    },
                },
 
                Status = "Active"
            },
            new Employee()
            {
                Id = Guid.NewGuid().ToString(),
                EmployeeId = 50011,
                FirstName = "Vishnu",
                LastName = "Vallapu",
                ContactNo = "99999999",
                Email = "Vishnuvallapu.something.com",
                Gender = "Male",
                Department = new List<Department.Department>()
                {
                    new Department.Department()
                    {
                        Id = Guid.NewGuid().ToString(),
                        DepartmentId = 01,
                        DepartmentName = "CEO",
                        Description = "Head of the Office",
                        Status = "Active",
                        CreateDateTime = DateTime.UtcNow,
                        ModifyDateTime = DateTime.UtcNow
                    },
 
                    new Department.Department()
                    {
                        Id = Guid.NewGuid().ToString(),
                        DepartmentId = 04,
                        DepartmentName = "Monitoring",
                        Description = "Checks all the work done by the employees",
                        Status = "In-Active",
                        CreateDateTime = DateTime.UtcNow,
                        ModifyDateTime = DateTime.UtcNow
                    }
                },
                Status = "Active"
            },
           
        };
 
        private List<Employee> _employeesList = new List<Employee>();
 
        public IEnumerable<Employee> GetAllEmployees()
        {
            if (ServerIsDown) return null;
 
            if (Convert.ToInt32(_MongoEmpCollection.Count()) > 0)
            {
                _employeesList.Clear();
                var employees = _MongoEmpCollection.FindAs(typeof(Employee), Query.NE("FirstName", "null"));
                if (employees.Count() > 0)
                {
                    foreach (Employee employee in employees)
                    {
                        _employeesList.Add(employee);
                    }
                }
            }
            else
            {
                #region add test data if DB is empty
 
                _MongoEmpCollection.RemoveAll();
                foreach (var employee in _testEmployeeData)
                {
                    _employeesList.Add(employee);
 
                    Add(employee); // add data to mongo db also
                }
 
                #endregion
            }
 
            var result = _employeesList.AsQueryable();
            return result;
 
        }
 
        public Employee Add(Employee employee)
        {
            if (string.IsNullOrEmpty(employee.Id))
            {
                employee.Id = Guid.NewGuid().ToString();
            }
            _MongoEmpCollection.Save(employee);
            return employee;
        }
 
        public bool Delete(int ObjectId)
        {
            _MongoEmpCollection.Remove(Query.EQ("EmployeeId", ObjectId));
            return true;
        }
 
        public Employee GetEmployeeById(int id = 0)
        {
            if (id == 0)
            {
                throw new ArgumentNullException("id", "Employee Id is empty!");
            }
            var employee = (Employee) _MongoEmpCollection.FindOneAs(typeof(Employee), Query.EQ("EmployeeId", id));
            return employee;
        }
 
        public bool Update(int objectId, Employee employee)
        {
            UpdateBuilder updateBuilder = MongoDB.Driver.Builders.Update
                .Set("EmployeeId", employee.EmployeeId)
                .Set("FirstName", employee.FirstName)
                .Set("LastName", employee.LastName)
                .Set("Email", employee.Email)
                .Set("ContactNo", employee.ContactNo)
                .Set("Gender", employee.Gender)
                .Set("Department..DepartmentName", employee.Department.DepartmentName)
                .Set("Department.Description", employee.Department.Description)
                .Set("Department.Status", employee.Department.Status)
                .Set("Department.CreateDateTime", employee.Department.CreateDateTime)
                .Set("Department.ModifyDateTime", employee.Department.ModifyDateTime)
                .Set("Status", employee.Status);
            // _MongoEmpCollection.Update()
 
            return true;
        }
 
    }
}



 Comments   
Comment by Jeffrey Yemin [ 03/Dec/20 ]

First, my apologies for not responding on this issue sooner.

It's likely that you've moved past this long ago, but for others with similar issues, here are some resources to get questions like this answered more quickly:

  • Our MongoDB support portal, located at support.mongodb.com
  • Our MongoDB community portal, located here
  • If you are an Atlas customer, there is free support offered 24/7 in the lower right hand corner of the UI

Thank you!

Generated at Wed Feb 07 21:40:54 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.