db.student.find().forEach(function(x){
//under normal circumstances, the field to obtain the Document is as follows
//Get Student Names
print(x.stuName);
//Obtain student age
print(x.stuAge);
});
//But I now have a requirement that this fieldName is dynamic.
//For example, I need to obtain different field values according to the passed fieldName.
//For example, I passed the string "stub" when calling this function
function handleField(fieldName){
db.student.find().forEach(function(x){
//Print out stuName
print(fieldName);
//print out undefined
print(x.fieldName);
});
}
Why the second method is not successful, is it an x.fieldName statement, this fieldName can only specify dead, and cannot obtain the corresponding field according to the dynamically passed-in value.
print(x[fieldName]);
In this way, this is a basic js problem and has nothing to do with mongodb.