0

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" 
    }
]

1 Answer 1

1

You can use $objectToArray in an aggregation pipeline:

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

Example here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.