mongodb - How to sort a collection using the last element of an array -


my problem that, have collection below, _id ignored

{ "value" : -10, "r" : [ { "v" : 1 }, { "v" : 3 } ] } { "value" : 2, "r" : [ { "v" : 4 }, { "v" : 1 } ] } { "value" : -100, "r" : [ { "v" : 4 }, { "v" : 1 }, { "v" : 10 } ] } { "value" : -3, "r" : [ ] } 

and sort last value of array r, say, want have result below,

{ "value" : -3, "r" : [ ] } # 1 should either first 1 or last 1 { "value" : 2, "r" : [ { "v" : 4 }, { "v" : 1 } ] } { "value" : -10, "r" : [ { "v" : 1 }, { "v" : 3 } ] } { "value" : -100, "r" : [ { "v" : 4 }, { "v" : 1 }, { "v" : 10 } ] } 

i know can sort first vaue of array r by

db.my.find().sort({'r.0.v': 1}) 

but how can last value?

and, if mongoengine model below

class v(embeddeddocument):     v = intfield()  class m(document):     value = intfiled     r = listfield(embeddeddocumentfield(v)) 

how should mongoengine? intfield maybe other fields such datetimefield, stringfield ...

thanks

if possible, i'd suggest (double) store value want sort on. put in array , in second field. whenever push new value array (or store array), add new field corresponding "last value in array" , index , sort on that. in example below, called lastr:

{ "value" : -10, "r" : [ { "v" : 1 }, { "v" : 3 } ], "lastr": 3 } { "value" : 2, "r" : [ { "v" : 4 }, { "v" : 1 } ], "lastr": 1 } { "value" : -100, "r" : [ { "v" : 4 }, { "v" : 1 }, { "v" : 10 } ], "lastr": 10 } { "value" : -3, "r" : [ ] } 

create index:

db.so.ensureindex({lastr: 1}) 

and use:

> db.so.find().sort({lastr: 1}) { "_id" : objectid("5203a1c83c5438af60de63a1"), "value" : -3, "r" : [ ] } { "_id" : objectid("5203a1ad3c5438af60de639f"), "value" : 2, "r" : [ { "v" : 4 }, { "v" : 1 } ], "lastr" : 1 } { "_id" : objectid("5203a1d33c5438af60de63a2"), "value" : -10, "r" : [ { "v" : 1 }, { "v" : 3 } ], "lastr" : 3 } { "_id" : objectid("5203a1b73c5438af60de63a0"), "value" : -100, "r" : [ { "v" : 4 }, { "v" : 1 }, { "v" : 10 } ], "lastr" : 10 } 

it far more versatile , expandable trying use aggregation solution (which have 16mb limit result set , makes far more complex retrieve complex documents when needing deal projection).


Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

php - MySQLi multi_query results for later use -