$arrayToObject not working for me in Atlas

I have documents with an structure similar to this (additional fields, but the structure of the title field is exactly the same)

 {
   "title": [
     {"language":"en","value":"Car"},
     {"language":"es","value":"Coche"}
   ]
 }

If I try to run this aggregation pipeline in atlas:

db.inventory.aggregate(
   [
      {
         $project: {
            title: { $arrayToObject: "$title" }
         }
      }
   ]
)

I get an ‘unknown error’ message.

Any idea? Is it broken, or what i’m trying to do is not supported?

The documentation here: https://docs.mongodb.com/manual/reference/operator/aggregation/arrayToObject/

shows a very similar case, so this is supposed to work.

Any help would be appreciated.

Hello @CarlosDC,

You have to read the instruction provided on top of the documentation $arrayToObject,

Converts an array into a single document; the array must be either:

  • An array of two-element arrays where the first element is the field name, and the second element is the field value:
[ [ "item", "abc123"], [ "qty", 25 ] ]

– OR -

  • An array of documents that contains two fields, k and v where:
    • The k field contains the field name.
    • The v field contains the value of the field.
[ { "k": "item", "v": "abc123"}, { "k": "qty", "v": 25 } ]

$arrayToObject has the following syntax:

{ $arrayToObject: <expression> }

The <expression> can be any valid expression that resolves to an array of two-element arrays or array of documents that contains “k” and “v” fields.


I am sure you are clear with above provided instruction in $arrayToObject.

For your case you can use $map to reconstruct array to array of two-element arrays where the first element is the field name, and the second element is the field value and than convert to object,

db.inventory.aggregate([
  {
    $project: {
      title: {
        $arrayToObject: {
          $map: {
            input: "$title",
            in: ["$$this.language", "$$this.value"]
          }
        }
      }
    }
  }
])
2 Likes

Thanks so much for your help Vishal! I would add that I didn’t suspect that ‘k’ and ‘v’ were like… fixed constants that one needs to use. My impression when reading the documentation was that any format of [ { “key1”:“value1”}, {“key2”:“value2”}… ] would work.

1 Like

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