Cesar Augusto
Cesar Augusto

Reputation: 278

MongoDB Convert sigle object to array of object based on key:value

Is there a way by using mongodb queries, convert a sigle object field to an array of object but key:value based?

Before

"fields" : {
    "field1" : 1,
    "field2" : true, 
    "field3" : false, 
    "field4" : "any string value"
}

After

"fields" : [
    {
        "name" : "field1",
        "value": 1
    }, 
    {
        "name" : "field2", 
        "value" : true
    }, 
    {
        "name" : "field3",
        "value" : false
    }, 
    {
        "name" : "field4",
        "value" : "any string value" 
    }
]

Upvotes: 0

Views: 67

Answers (1)

J.F.
J.F.

Reputation: 15235

You can use $objectToArray in an aggregation pipeline:

db.collection.aggregate([
  {
    "$set": {
      "fields": {
        "$objectToArray": "$fields"
      }
    }
  }
])

Example here

Upvotes: 1

Related Questions