Getting the document field names and adding them as nested fields in an Aggregation pipeline

Im writing a mongodb aggregate pipeline. My documents are of the form below :


{
  name: "01"
  tags {
  tag_01: {
    a: "a01-val",
    b: "b01-val"
  },
  tag_02: {
    a: "a02-val",
    b: "b02-val"
  }
  }
},
{
  name: "02"
  tags {
  tag_03: {
    a: "a03-val",
    b: "b03-val"
  },
  tag_04: {
    a: "a04-val",
    b: "b04-val"
  }
  }
}

My pipeline should generate documents as below ( Notice the new field tagName added )

{
  name: "01"
  tags {
  tag_01: {
    a: "a01-val",
    b: "b01-val",
    tagName: "tag_01"
  },
  tag_02: {
    a: "a02-val",
    b: "b02-val",
    tagName: "tag_02"
  }
  }
},
{
  name: "02"
  tags {
  tag_03: {
    a: "a03-val",
    b: "b03-val",
    tagName: "tag_03"
  },
  tag_04: {
    a: "a04-val",
    b: "b04-val",
    tagName: "tag_04"
  }
  }
}

In other words, a new field is added inside each subdocument whose value is the name of the parent field. Is it possible to do this?

The major issue with your model is that you have dynamic values as field names. This makes queries hard to do and almost makes it impossible to use indexes.

The first you will have to do is to use a $set stage that uses $objectToArray. This should give you a tags object that looks like:

tags: 
      [ { k: 'tag_01', v: { a: 'a01-val', b: 'b01-val' } },
        { k: 'tag_02', v: { a: 'a02-val', b: 'b02-val' } } ]

You should then be able to set tagName: in v: using the value of k:. You could then use $arrayToObject to returns to the original form.

I just hope that this aggregation will be use to permanently update your model to something that is more usable.

And, next time you publish redacted documents, please redact without syntax error. It is a little bit annoying when we have to edit published documents before we can use them to experiment.

Thank You very much Steevej.
I was able to solve the issue based on what you said.
Sorry, I did not notice the syntax error. ( What I posted was an equivalent problem I was trying to solve at work - did not want to post anything from work verbatim )
Thank you again

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.