How to build a query that returns all entities sorted desc by count embedded post ids?
Sample data:
{ "_id" : ObjectId( "5090f8061e7bf28095000012" ),
"name" : "test",
"post_ids" :
[ ObjectId( "5090f8061e7bf28095000010" ) ],
[ ObjectId( "5090f8061e7bf28095000011" ) ] },
{ "_id" : ObjectId( "5090f8061e7bf28095000012" ),
"name" : "test2",
"post_ids" : [
ObjectId( "5090f8061e7bf28095000010" ),
ObjectId( "509104ec1e7bf2989b00000b" ),
ObjectId( "509105001e7bf2989b00000f" ) ] }
#my actual query returns only count:
tags_by_count = Tag.desc(:post_ids).count
I don’t think this is possible in MongoDB. Everything I’m reading suggests creating a second field for the length of the array and indexing that.
This is a little old, but might still be relevant:
https://groups.google.com/forum/?fromgroups=#!topic/mongodb-user/zSSnj6ldfLE
Also, even if it were possible, it would be slow because it would require using javascript instead of an index sort, since you definitely can’t index array length.