1

DB Sample...

 { "code" : "2156",
    "trades" : [ 
        {
            "close" : 78000,
            "date" : "2017.11.08"
        }, 
        {
            "close" : 25300,
            "date" : "2017.08.07"
        }, 
        {
            "close" : 74900,
            "date" : "2017.11.07"
        }
    ] 
 },
  { "code" : "2158",
    "trades" : [ 
        {
            "close" : 79000,
            "date" : "2017.11.08"
        }, 
        {
            "close" : 24300,
            "date" : "2017.08.07"
        }, 
        {
            "close" : 71900,
            "date" : "2017.11.07"
        }
    ] 
 }

Above is my exist mongodb data sample. What I want to do is arrange objects in trades by date asc. So It should be arrange like this

    "trades" : [ 
        {
            "close" : 24300,
            "date" : "2017.08.07"

        }, 
        {
            "close" : 71900,
            "date" : "2017.11.07"
        }, 
        {
            "close" : 79000,
            "date" : "2017.11.08"
        }
    ] 

Is there any way to do this? I'm using Node.js and Mongoose. I already check this article :

how to sort array inside collection record in mongoDB

But it looks like not ordering db itself, it just query db to certain conditions, right? Is there a way to ordering db itself?

s7vr
  • 73,656
  • 11
  • 106
  • 127
ton1
  • 7,238
  • 18
  • 71
  • 126

2 Answers2

1

You can $sort modifier to order the elements in an array. multi:true to apply updates to multiple documents.

Something like

db.collection_name.update( { }, { $push: { trades: { $each: [ ], $sort:{date:1}} } }, {multi: true } )
s7vr
  • 73,656
  • 11
  • 106
  • 127
0

"Ordering the DB" is really not necessary. If you create indexes on the fields you want to query by, MongoDB will effectively "order" these for you.

Here's MongoDB's instructions on creating indexes: https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/

Since you tagged this with node.js, I assume you're using mongoose. In which case you can add {index: true} to your schema definition.

Mongoose's instructions on defining indexes for schemas: http://mongoosejs.com/docs/3.4.x/docs/guide.html#indexes

Jim B.
  • 4,512
  • 3
  • 25
  • 53