MongoDb order by to be computed value
What I would like to do with MongoDB is sort my collection 'tweets' on an integer field 'points', but I want to remove the number of seconds from the number of points, g开发者_如何学运维iven the difference between the time now, and the time the tweet was created. So order by (points - time difference).
It depends therefore on the time when the query is run. Older tweets would end up having lower points.
Could someone show me an example of this in MongoDB (in PHP)?
MongoDB does not function
in the sort()
command.
In fact, performing a simple find objects where object.a > object.b
requires use of the un-indexed $where clause.
The way around this right now is to actually calculate that field and then sort on it.
So in your case, you would have a new field with the value of (points-time). Please note that if you plan to sort on this data, you will probably want that field to be indexed. Trying to sort on a large number of un-indexed fields can be very slow.
AFAIK, sort()
does not take a function
, so there is not much you can do about it. You might want to consider doing the ordering by time difference in your app layer.
$m = new Mongo(); // connect
$collection = 'collection_name';
$db = $m->selectDB('mongodb_name');
$cursor = $db->$collection->find();
$cursor->sort(array('day' => -1));
$items = iterator_to_array($cursor);
This post may help.
MongoDB get all fields + sort by value computed from multiple fields
The basic idea is that it creates a new object with a new property computed from the old object. It then sorts the new objects and returns the result.
精彩评论