-
Type: New Feature
-
Resolution: Done
-
Priority: Major - P3
-
Affects Version/s: None
-
Component/s: Aggregation Framework
-
Fully Compatible
-
v3.4
-
Query 2017-03-06
-
(copied to CRM)
In many cases, it would be useful to convert an object to an array. We should add an aggregation expression to do so. For example, it could be called $objectToArray, and do something like this:
> db.foo.insert({_id: 0, subDoc: {a: 1, b: 3, c: "example"}}); > db.foo.aggregate([{$project: {expanded: {$objectToArray: "$subDoc"}}}]) {_id: 0, expanded: [{k: "a", v: 1}, {k: "b", v: 3}, {k: "c", v: "example"}]}
Original Description
Currently, if a collection contains the following document:
{_id: 0, data: {a: 1, b: 2, c: 3}}
There is no way to unwind that one document into the following three documents:
{_id: 0, data: {a: 1}} {_id: 0, data: {b: 2}} {_id: 0, data: {c: 3}}
One way to accomplish this would be to add a stage to unwind documents, e.g.
db.coll.aggregate([{$objectToArray: {field: '$data'}}])
Which would yield the following document, which could then be unwound to produce the desired result:
{_id: 0, data: [{a: 1}, {b: 2}, {c: 3}]}
- is depended on by
-
CSHARP-1939 Add an aggregation expression to convert an object to an array of key, value pairs
- Closed
- is duplicated by
-
SERVER-5947 Add ability to project key names as values and values as key names
- Closed
-
SERVER-11392 $unwind on subdocuments
- Closed
- is related to
-
SERVER-23310 Add an expression to convert an array of pairs to an object
- Closed
-
SERVER-2507 variable field name in queries
- Backlog
- related to
-
DRIVERS-358 Aggregation Framework Support for 3.6
- Closed
-
SERVER-27774 Add $of for iterating over object keys
- Closed
- links to