0

All! My document has such structure:

{
    fname: value,
    lname: value,
    city: value
}

When I use find() method, I get result in default order fname, lname, city. But I want to get result in other order of field, such as: city, fname, lname. Does mongodb allow fields ordering in result?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • 1
    I'm curious why you care about the order of the fields. You may be trying to solve the wrong problem. – JohnnyHK Nov 07 '14 at 14:33

3 Answers3

1

Yes and no. To really do this sort of manipulation you need the aggregation framework. Even then it's a bit tricky since you must "rename" the fields in order to change their order. This is because there are general optimizations in place that "copy" content from one "pipeline" stage to another. This is considered optimal.

But you can always do this:

db.collection.aggregate([
    { "$project": {
        "tcity": "$city",
        "tfname": "$fname",
        "tlname": "$lanme"
    }},
    { "$project": {
        "city": "$tcity",
        "fname": "$tfname",
        "lname": "$tlname"
    }}
])

Very contrived, but that is the way you have to do it. Or otherwise just live with a single projection for the "renamed" fields in the order you want and then just "rename" again in code.

Or of course, your code can simply "re-map" the field names from the result of a query.

But the basic point is that MongoDB itself "preserves" the original order of fields as an "optimization" to how they are stored and does not mess with the output otherwise. If you want to you can, but you need to take the steps as shown in order to do so.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • But will this projection bet sorted by default or we need to call the sort() method. – vmr Nov 07 '14 at 10:56
  • @vmr Order of fields and sorting of results are two different things. Sort is applied to content not the field names. I think the general consensus here is that while you "can" force MongoDB to output fields in specific order, the general way you "should" be handling is is "after" the results are returned. I'm only showing that you "can" to show that it's pretty ridiculous to do so. – Neil Lunn Nov 08 '14 at 00:37
1

You can use .sort(). eg:

db.stocks.find().sort( { ticker: 1, date: -1 } )

For more info see http://docs.mongodb.org/manual/reference/method/cursor.sort/

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
volatile
  • 39
  • 5
0

I assume you are referring to the output as it shows up in the Mongo shell? If so, you can assign the returned output to a variable (cursor, I believe) and step through your cursor afterwards while outputting the individual field variables in any order you like.

alernerdev
  • 2,014
  • 3
  • 19
  • 35