Field order of output

I expect that the output would be in the order of the fields in the $project stage. I am used to being control the order of the fields in the project clause in a regular find query.

In this example from class. This query:
“$project”: {
“_id”: 0,
“name”: 1,
“hasMagneticField”: 1,
“numberOfMoons”: 1
}, {
“$sort”: { “hasMagneticField”: -1, “numberOfMoons”: -1 }
{ “name” : “Jupiter”, “numberOfMoons” : 67, “hasMagneticField” : true }

In both the $project and $sort stage hasMagnetic field is listed before numberOfMoons, but in the resulting document numberOfMoons appears first. This appears to be the order in the documents themselves. Is there a way to control the order of the fields in the resulting document?

By definition a document is an unordered set of name value pair. There is no advantage and a potential overhead in changing the natural order of the fields. We should not forget that we are in the shell (or in the driver) at the data layer so the order has no importance. If the order is important it has to be done at the presentation layer.



@steevej-1495 is absolutely right.

José Carlos

1 Like

Thanks, Steve and José. That’s perfectly reasonable. The scenario I had in mind was using the Aggregation framework as part of transformation and cleanup of legacy data. Let’s say we have this legacy database. We import it raw just to get it into a MongoDb collection so we can use the framework. In the end we want our new collection to have the fields exactly how we want them, so we are imposing a new natural order on the fields in the document. This way we don’t have some random ordering due to the legacy database and how fields may have been added at different stages in the pipeline.

I guess we can use the aggregation pipeline to do most of the work and then write a simple function that traverses the resulting documents and creates a new set of documents in the field order we want, but was wondering if we could do it all with the framework.


In that case a final projection where you reshape the documents with the fields in the order you want would work.

José Carlos