0

How can I arrange the fields of the documents returned by the output of the find query in a certain format?

Let's assume that by default, the find query returns the fields in the following format:

{ "_id" : 2, "name" : "bob", "status" : "A" }
{ "_id" : 3, "name" : "ahn", "status" : "A" }
{ "_id" : 6, "name" : "abc", "status" : "A" }

However, I want it to return it in the following order/arrangement of the fields

{ "_id" : 2, "status" : "A", "name" : "bob" }
{ "_id" : 3, "status" : "A", "name" : "ahn" }
{ "_id" : 6, "status" : "A", "name" : "abc" }
Temp O'rary
  • 5,366
  • 13
  • 49
  • 109
  • "arrange fields" where exactly? It's just a json - "an **unordered** collection of zero or more name/value pairs" https://tools.ietf.org/html/rfc7159 – Alex Blex Jun 05 '18 at 12:06
  • It also really depends. In languages like Python or Perl there is a strong distinction between Dicts/Hashes and variants of those with "ordered keys". Generally the implementation of the driver here, and the JSON spec and the BSON spec is that these keys have no set order and you should really not be expecting it to maintain as such. You "can" **force** it somewhat with a `$project`, but it's not a "language proof" guarantee that it actually presents that way. – Neil Lunn Jun 05 '18 at 12:23
  • I don't think you can do that with a plain `find`, even using projection. – Marco Luzzara Jun 05 '18 at 12:25
  • @MarcoLuzzara The point I just made is there is "no guarantee" you can actually do it with `aggregate()` either. You can state what you "prefer", but especially if you render that as JSON and then read in something else, then it's simply not guaranteed it will stay that way. Nor should you "really care" for that matter. Wasted too much time on this already. – Neil Lunn Jun 05 '18 at 12:27

0 Answers0