2

How do I query for everyone who has a nickname and replace the nickname key with just "nick"

Dataset looks like this with a lot more fields and a lot more documents. the nickname obj is in an unknown index if it exists.

{
  _id: "robert",
  properties: [
    {
      "kids": 3
    },
    {
      "nickname": "Bob"
    },
    {
      "age": 45
    }
  ]
}

{
  _id: "alice",
  properties: [
    {
      "kids": 3
    },
    {
      "age": 45
    }
  ]
}

{
  _id: "joseph",
  properties: [
    {
      "nickname": "joe"
    }
  ]
}

In the end it should be:

{
  _id: "robert",
  properties: [
    {
      "kids": 3
    },
    {
      "nick": "Bob"
    },
    {
      "age": 45
    }
  ]
}

{
  _id: "alice",
  properties: [
    {
      "kids": 3
    },
    {
      "age": 45
    }
  ]
}

{
  _id: "joseph",
  properties: [
    {
      "nick": "joe"
    }
  ]
}
1

1 Answer 1

1

The following query can do the trick. We are aggregating over collection to change the field properties.nickname to properties.nick and replacing existing data of collection with the aggregation output.

db.collection.aggregate([
  {
    $addFields:{
      "properties":{
          $map:{
          "input":"$properties",
          "as":"property",
          "in":{
            $mergeObjects:[
              "$$property",
              {
                "nick":"$$property.nickname"
              }
            ]
          }
        }
      }
    }
  },
  {
    $project:{
      "properties.nickname":0
    }
  },
  {
    $out:"collection"
  }
])

Before:

{
  "_id" : "robert",
  "properties" : [
    {
      "kids" : 3
    },
    {
      "nickname" : "Bob"
    },
    {
      "age" : 45
    }
  ]
}
{
  "_id" : "alice",
  "properties" : [
    {
      "kids" : 3
    },
    {
      "age" : 45
    }
  ]
}
{ "_id" : "joseph", "properties" : [ { "nickname" : "joe" } ] }

After:

{
  "_id" : "robert",
  "properties" : [
    {
      "kids" : 3
    },
    {
      "nick" : "Bob"
    },
    {
      "age" : 45
    }
  ]
}
{
  "_id" : "alice",
  "properties" : [
    {
      "kids" : 3
    },
    {
      "age" : 45
    }
  ]
}
{ "_id" : "joseph", "properties" : [ { "nick" : "joe" } ] }
Sign up to request clarification or add additional context in comments.

2 Comments

What versions of mongodb does this work with? I don't have 4.2 yet.
Tried with MongoDB 4.4. It's wotking.

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.