1

let's say I have docs such as

{
  "nickname": "my nickname",
  "comments": [
    {
      "id": 1
    },
    {
      "id": 1
    }
  ]
}

how do I update it to look like

{
  "nickname": "my nickname",
  "comments": [
    {
      "id": 1,
      "nickname": "my nickname"
    },
    {
      "id": 1,
      "nickname": "my nickname"
    }
  ]
}

This does not seem to be working

db.getCollection('users').update(
{
    "comments.nickname": null
},
     { "$set": { "comments.$.nickname": "$nickname" } });

This is just an example to represent my problem.

I would not like to hear about re-structuring and optimizing the fields.

Thanks!

1 Answer 1

2

Try this (v4.2):

db.users.updateMany(
    {"comments.nickname":null},
    [
        {"$set": {"comments.nickname": "$nickname"}}
    ]
)

Note: It will override if any comments.nickname already exists


db.users.aggregate([
  {
    $match: {
      "comments.nickname": null
    }
  },
  {
    $addFields: {
      comments: {
        $map: {
          input: "$comments",
          in: {
            id: "$$this.id",
            nickname: {
              $cond: [
                "$$this.nickname",
                "$$this.nickname",
                "$nickname"
              ]
            }
          }
        }
      }
    }
  },
  {
    $out: "users"
  }
])

Note: It will keep already existing values

Sign up to request clarification or add additional context in comments.

Comments

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.