Introduction to MongoDB $objectToArray Operator

$objectToArray is an aggregation operator in MongoDB that transforms a document into an array containing key-value pairs of that document. Each element in the array is a document with two fields: k and v, representing the key and value of the original document, respectively.

Syntax

The syntax of the $objectToArray operator is as follows:

{ $objectToArray: <expression> }

Here, <expression> is the document expression to be converted to an array, which can be a document field, an aggregation expression, etc.

Use cases

The $objectToArray operator can be used in the following scenarios:

  • Transforming a document into an array for easy manipulation in the aggregation pipeline.
  • Dynamically accessing and manipulating the keys and values of a document.

Examples

Example 1

The following aggregation pipeline uses the $objectToArray operator to transform a document into an array containing key-value pairs of that document:

db.collection.aggregate([
  {
    $project: {
      myDoc: {
        name: "Tom",
        age: 18,
        gender: "male"
      },
      myArray: { $objectToArray: "$myDoc" }
    }
  }
])

After executing the above pipeline, the output is as follows:

{
  "myDoc": {
    "name": "Tom",
    "age": 18,
    "gender": "male"
  },
  "myArray": [
    {
      "k": "name",
      "v": "Tom"
    },
    {
      "k": "age",
      "v": 18
    },
    {
      "k": "gender",
      "v": "male"
    }
  ]
}

Example 2

The following aggregation pipeline uses the $objectToArray and $group operators to group documents in a collection based on fields and count the number of documents in each group:

db.collection.aggregate([
  {
    $project: {
      myDoc: {
        name: "$name",
        age: "$age",
        gender: "$gender"
      }
    }
  },
  {
    $group: {
      _id: { $objectToArray: "$myDoc" },
      count: { $sum: 1 }
    }
  }
])

After executing the above pipeline, the output is as follows:

{
  "_id": [
    {
      "k": "name",
      "v": "Tom"
    },
    {
      "k": "age",
      "v": 18
    },
    {
      "k": "gender",
      "v": "male"
    }
  ],
  "count": 1
}
{
  "_id": [
    {
      "k": "name",
      "v": "Lucy"
    },
    {
      "k": "age",
      "v": 20
    },
    {
      "k": "gender",
      "v": "female"
    }
  ],
  "count": 2
}

Conclusion

In MongoDB, the $objectToArray operator transforms an object into an array containing key-value pairs. It can be used to convert fields containing objects into arrays for manipulation in the aggregation pipeline. By converting fields into arrays, other operators and operators in the aggregation pipeline can be used to manipulate them, which is very useful in certain situations.