Home > OS >  MongoDB: returning dynamic field from the result
MongoDB: returning dynamic field from the result

Time:10-06

Consider a collection,

MongoDB Enterprise rs0:PRIMARY> db.col.find({});
{ "_id" : 1, "height" : 150, "weight" : 60 }

I want to write a function to dynamically return the field value based on input.

function getFieldValue(inputField){
    
    var resultDoc = db.col.findAndModify({
        query:{_id: 1 },
        update: {$inc:{[inputField]:1}},
        new:true
        });
    
    return resultDoc;
}

This will return the whole document. How can I return only the field that was passed as input?

MongoDB Enterprise rs0:PRIMARY> var x = getFieldValue("weight")
MongoDB Enterprise rs0:PRIMARY> x
61

I tried resultDoc.[inputField], but that causes syntax error.

CodePudding user response:

You dont need the dot in resultDoc.[inputField] so it would be resultDoc[inputField].

  • Related