ton1
ton1

Reputation: 7628

How to update to order the elements of an array?

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?

Upvotes: 1

Views: 60

Answers (2)

s7vr
s7vr

Reputation: 75924

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 } )

Upvotes: 1

Jim B.
Jim B.

Reputation: 4694

"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

Upvotes: 0

Related Questions