Find value inside a collection in mongoose from nested json

Suppose I have data stored in collection Teacher as:

{
    "name":"john",
    "age":45,
    "class_access":{
        1234:"head",
        1235:"head
    },
    "_id" : ObjectId("12312312"),
}

{
    "name":"henry",
    "age":55,
    "class_access":{
        1234:"head",
    },
    "_id" : ObjectId("sdf9991"),
}

{
    "name":"travis",
    "age":35,
    "class_access":{
        2341:"head",
    },
    "_id" : ObjectId("sas21"),
}

I want to find all the information of all the teachers belonging to class 1234.

For this I tried:

 const TeacherDetails = await Teacher.find({ class_access: {1234:"head"} })

But it doesn't return anything. So how can I access nested json to get all the details?

If any one needs any further information do let me know.

As per solution provided by Mr. Arif const TeacherDetails = await Teacher.find({ "class_access.1234": "head" });

Support class value is not constant say I'm getting it from variable

const className = 1234

Now if I try, fetching className, it gives syntax error, I tried following syntax error for all of them

const TeacherDetails = await Teacher.find({ class_access.className: "head" });

const TeacherDetails = await Teacher.find({ class_access[className]: "head" });

const TeacherDetails = await Teacher.find({ 'class_access.+'${className}': "head" });

So how can we do it dynamically?

Answers 1

  • Since class_access represent object which may have multiple keys, you should try like

    You can use [variableName] as key like following

    method 1: Using string template

    const className = 1234
    const TeacherDetails = await Teacher.find({ [`class_access.${className }`]: "head" });
    

    method 2: Using string concatenation

    const className = 1234
    const classAccess = 'class_access.' + className;
    const TeacherDetails = await Teacher.find({ [classAccess] : "head" });
    

Related Articles