2

Is it possible to use a variables in MongoDB's query like this?

var FOO="123";
var BOO="323";
user.findOneAndUpdate({_id: userID},{$set:{FOO:BOO}}

BOO - the value, is working fine and it's being assign, while FOO - the key is not.

1
  • No, in MongoDB Foo is not a variable but a key "FOO" not FOO Commented Jan 7, 2018 at 11:28

1 Answer 1

5

In MongoDB as such no functionality but you can do this in javascript like this

    var FOO="123";
    var BOO="323";
    user.findOneAndUpdate({_id: userID},{$set:{[FOO]:BOO}}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your answer, could you explain why this syntax actually works?
@AndriySimonov you can read here
@ManjeetThakur Thanks - PhpStorm doesn't recognize this syntax...but the code is running ..
@RoyBarOn Please accept the answer if this is working for you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.