1

I know I can use the pipeline aggregator within update to update the field of one value with the value from another field. However, my issue is when updated a field value based on the value of a nested field. The result of the update always issues the new field with brackets. I don't want brackets/array, I just want it to be a value. See code below https://mongoplayground.net/p/7ZDP8CYtKK3

db={
 "players": [
   {
     "_id": ObjectId("5fba17c1c4566e57fafdcd7e"),
     "username": "moshe",
     "health": 0,
     "maxHealth": 200,
     "Chapters": [
       {"Cat A": 25,
        "Cat B": 100,
        "Cat C": 125}]
   }
 ]
}

Here's the query I apply below

db.players.update(
{username: "moshe"},
[{"$set": {"health": "$Chapters.Cat A"}}]
)

The result yields

[{"Chapters": [
      {"Cat A": 25,
       "Cat B": 100,
       "Cat C": 125}],

    "_id": ObjectId("5fba17c1c4566e57fafdcd7e"),
    "health": [25],
    "maxHealth": 200,
    "username": "moshe"
  }]

What I want is for the update to health to appear without array brackets as so.... "health":25

Again this is an example based on a much much larger DB I'm working with.

turivishal
  • 34,368
  • 7
  • 36
  • 59

1 Answers1

0

You can use $arrayElemAt or $first(v4.4) operators to select the first element from an array,

db.players.update(
  { username: "moshe" },
  [{ 
    "$set": { 
      "health": {
        "$arrayElemAt": ["$Chapters.Cat A", 0]
      }
    } 
  }]
)

Playground

turivishal
  • 34,368
  • 7
  • 36
  • 59