0

I am trying to sort an inner array by date field, however, I couldn't make it. Here is an example document I have.

{
    "_id" : "BTC-ADX",
    "parity" : "BTC-ADX",
    "data" : [
        {
            "open" : 0.001,
            "high" : 0.002,
            "close" : 0.0015,
            "low" : 0.0012,
            "date" : ISODate("2018-03-16T05:00:00Z")
        },
        {
            "open" : 265,
            "high" : 397,
            "low" : 190,
            "close" : 125,
            "date" : ISODate("2018-03-16T06:00:00Z")
        },
        {
            "open" : 265,
            "high" : 397,
            "low" : 190,
            "close" : 125,
            "date" : ISODate("2018-03-16T07:00:00Z")
        },
        {
            "open" : 265,
            "high" : 397,
            "low" : 190,
            "close" : 125,
            "date" : ISODate("2018-03-16T06:30:00Z")
        }
    ]
}

Additionally, I have an index like;

{
    "v" : 1,
    "unique" : true,
    "key" : {
        "parity" : 1,
        "data.date" : -1
    },
    "name" : "parity_1_data.date_-1",
    "ns" : "crypto.stockentities"
}

And this is the query I am running

db.stockentities.find({_id:"BTC-ADX"}).sort({ parity:1, "data.date":-1 }).pretty()

But this query returns the same order I have shared above.

Thanks for your help!

quartaela
  • 2,579
  • 16
  • 63
  • 99
  • 1
    Sorting operates at the document level, not within an array field. Possible dupe of https://stackoverflow.com/questions/15388127/mongodb-sort-inner-array – JohnnyHK Mar 05 '18 at 01:53
  • @JohnnyHK thanks. I checked that topic before. So, my questions is then why mongodb allows you to create indexes on inner fields if sorting only operates on document level? – quartaela Mar 05 '18 at 01:57
  • That index would be used in a query on `data.date`. – JohnnyHK Mar 05 '18 at 01:59

1 Answers1

0

I used aggregate as @JohnnyHK suggested.

db.stockentities.aggregate( {$match : {parity: "BTC-ADX"}}, {$unwind: "$data"}, {$sort: {'data.date': -1}}, {$limit: 1} )

However, I am not sure if aggregate uses indexes. So, this approach might have performance issues.

quartaela
  • 2,579
  • 16
  • 63
  • 99