4

I'm using a version of mongodb that doesn't support $objectToArray.

In later versions of mongodb I am successfully using the following snippet in an aggregation pipeline:

{
  $project: {
    _id: 1,
    arr: {
      $objectToArray: "$obj"
    }
  }
}

Other answers suggest using objectToArray (sic) or scripting languages (python) or mongo solutions outside of the aggregation pipeline.

Is there a way to use map/reduce or something similar in earlier versions of mongo inside the aggregation pipeline?

Data input:

[
  {
    "id": "0",
    "obj": {
      "obj-0": {"prop": "value"},
      "obj-1": {"prop": "value"}
    }
  }
]

Desired result:

[
  {
    "id": "0",
    "arr": [
      {"prop": "value"},
      {"prop": "value"}
    ]
  }
]
Queenvictoria
  • 371
  • 5
  • 19
  • Possible duplicate of [MongoDB Get names of all keys in collection](https://stackoverflow.com/questions/2298870/mongodb-get-names-of-all-keys-in-collection) – Saravana Jan 17 '18 at 04:02
  • Hi @Saravana are you suggesting "You could do this with MapReduce" is a duplicate? Obviously another answer in that question is "use objectToArray" which I can't use (see my question). If you can use map reduce please could you explain how given the above example (an aggregation stage). – Queenvictoria Jan 17 '18 at 04:55
  • @Queenvictoria Can you add the sample data and expected result? – Neodan Jan 17 '18 at 07:46
  • No map reduce is not applicable here as we have nothing to reduce here. Something like in javascript. `var arr = []; db.collection.find({}, {obj:1}]).forEach( function(myDoc) { for(var key in myDoc.obj){ arr.push(myDoc.obj[key]); }} )` – s7vr Jan 19 '18 at 13:33

0 Answers0