Martin Allusse
Martin Allusse

Reputation: 115

How to duplicate fields in document in MongoDB?

I am trying to duplicate some fields inside documents.
In the case we have fields in object, I want to duplicate them outside and vice versa.
My MongoDB version is 4.2.12.

Here is my collection :

{
    'id': '1',
    'object': {
        'a': 'OK',
        'b': ''
    }
},
{
    'id': '2',
    'a': '',
    'b': 'OK',
}

Here is what I want as a result :

{
    'id': '1',
    'a': 'OK',
    'b': '',
    'object': {
        'a': 'OK',
        'b': ''
    }
},
{
    'id': '2',
    'a': '',
    'b': 'OK',
    'object': {
        'a': '',
        'b': 'OK'
    }
}

Your help will be highly appreciated.

Upvotes: 1

Views: 739

Answers (1)

NeNaD
NeNaD

Reputation: 20304

  • $addFields to add new fields
  • $cond with $ifNull to check if the field already exists or not
db.collection.aggregate([
  {
    "$addFields": {
      "a": {
        "$cond": {
          "if": { "$ifNull": [ "$a", null ] },
          "then": "$a",
          "else": "$object.a"
        }
      },
      "b": {
        "$cond": {
          "if": { "$ifNull": [ "$b", null ] },
          "then": "$b",
          "else": "$object.b"
        }
      },
      "object": {
        "$cond": {
          "if": { "$ifNull": [ "$object", null ] },
          "then": "$object",
          "else": { a: "$a", b: "$b"}
        }
      }
    }
  }
])

Working example

Upvotes: 1

Related Questions