skip to Main Content

I have this mongo query

db.getCollection("users").updateMany({ _id: ObjectId('65d8fd25618ef79985233636') }, { $set: { questionAnswers: { hobbies: "$hobbies", islandItems: "$islandItems", superPower: "$superPower" }}})
I am trying to set variables that already exist on this user object to be inside of a new json object called questionAnswers, it works in the sense of it will create that object but the values are not copying over from the variables it is just setting it to a string that is legit the "$islandItems" with the dollar sign in it.

Any help is appreciated!

I have tried changing the quotes and everything to see if that helps. Im expecting that it fills the new variables with the old ones

2

Answers


  1. Starting with mongo 4.2 you can do aggregation pipeline with updates . Notice the brackets [] in the update parameter

    then your query would look something like

    db.collection.update({
      _id: ObjectId("65d8fd25618ef79985233636")
    },
    [
      {
        $set: {
          questionAnswers: {
            hobbies: "$hobbies",
            islandItems: "$islandItems",
            superPower: "$superPower"
          }
        }
      }
    ])
    

    playground

    Login or Signup to reply.
  2. You shouldn’t use the quotes or dollar signs for variables. Try:

    { hobbies: hobbies, islandItems: islandItems, superPower: superPower }

    You may have been confusing the way JS handles variables inline in strings, which looks like ${variable}.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search