Mongoid limit parameter ignored - mongodb

I tried to grab the latest N records with a unique value (first_name).
So far:
#users = User.all(:limit => 5, :sort => [:created_at, :desc]).distinct(:first_name)
almost works..But ignores the limit and sort order
Also:
#users = User.limit(5).desc(:created_at).distinct(:first_name)
Ignores both 'limit' and 'desc'
#users = User.limit(5)
Works..
What am I doing wrong?
Any help would be greatly appreciated!

I played with this for a little while and this is the best I could come up with.
Good luck.
#users = User.desc(:created_at).reduce([]) do |arr, user|
unless arr.length == 5 || arr.detect{ |u| u.first_name == user.first_name }
arr << user
end
arr
end

Have you tried using a pagination gem such as amatsuda / kaminari and limiting the results using page().per()?

Both distinct and count ignore the limit command in Mongoid. With count you can pass true (i.e. User.limit(5).count(true)) to force it to pay attention to the scope. Unfortunately there is no such trick for distinct as far as I'm aware (see docs/source here).
If you want to just grab the first 5 first_name's you can do this (not distinct):
User.desc(:created_at).limit(5).map(&:first_name)
This will respect the limit, but still load 5 full objects from the database (then discard the rest of the object to give you full name). If you actually need to run distinct, you're better off heading toward an aggregation framework solution.
I haven't tested, but this seems to be what you're looking for: https://stackoverflow.com/a/17568267/127311

I played with some result I found this.
User.limit(2).count => 10 #but in array I found only two results
User.limit(2).to_a.count => 2
May be limit gives the correct result, but count query gives wrong result.

Related

How to update JSON node that matches criteria based on attribute value (instead of index)?

Postgresql 10+
Example from the documentation...
jsonb_set('[{"f1":1,"f2":null},2,null,3]', '{0,f1}','[2,3,4]', false)
results in...
[{"f1":[2,3,4],"f2":null},2,null,3]
Fair enough. But I need to find my target node by attribute value, not index. For the life of me, I cannot figure out how do something like...
jsonb_set('[{"f1":1,"f2":null},2,null,3]', '{(where f1 = 1),f1}','[2,3,4]', false)
Any advice on how to accomplish this?
Thanks!
You can split the steps into two jobs:
Split in elements (jsonb_arral_elements)
Indentify wich elements must change (case when...)
Update that element (jsonb_set)
Join all together (jsonb_agg)
solution
select jsonb_agg(case when element->>'f1'='1' then jsonb_set(element, '{f1}', '[2,3,4]') else element end)
from jsonb_array_elements('[{"f1":1,"f2":null},2,null,3,{"f1":3},{"f1":1,"f2":2}]'::jsonb) element
note
I changed the input adding two more elements with "f1" key

Dynamic query in EF

I have already searched in other questions for a solution, but didn't find it.
So, my problem is the following:
I have a page where the user can mount an expression. For example, if they want some professors with course 1 and course 2 then, they create an expression like this:
(course 1 AND course 2) in the page.
But when I use EF, if I put the "AND", I get no professor... if I change to "OR" I get some professors with 1 or 2 and maybe one of then have two courses.
I need the professors who have always the two courses (course 1 AND course 2)
How can I accomplish this?
(If my explanation get too confusing, let me know, I'll try in a other way!)
I tried to understand your explanation, Try something as following and let usknow if is the logic you are looking for? or you want something other result.
from x in db.professors.Where(x => x. professorId == professorId && (x.courseid == 'course1' && x.ukat == 'course2'))
Maybe:
var result = db.Professors.Where(p =>
p.Cursos.Count(c => searchedCourses.Contains(c.CourseId)) == searchedCourses.Count());
This way you get all the professors, filter their courses to match that in the specified search, and get only the professors with the same amount of filtered courses and the searched ones.

Sphinx SetSortMode EXPR

I am trying to sort using Sphinx (PHP) to show in order of price but when I do it will show £10 before £1.75 so I need to use ABS like in mySQL.
I have tried this:
$s->SetSortMode (SPH_SORT_EXPR, "ABS(display_price) ASC" );
It doesnt seem to work though.
Can anybody help?
Check, if display_price attribute treated as a decimal in search index
Probably you have
sql_attr_string = display_price
instead of
sql_attr_float = display_price
or
sql_attr_bigint = display_price
updated
SPH_SORT_EXPR is ALWAYS descending order. the ASC/DESC are for use with EXTENDED mode only.
To 'invert' it to become acsending, can build it into the expression.
$s->SetSortMode (SPH_SORT_EXPR, "1000000-CEIL(ABS(display_price*100.0))" );

use of variable causes update to run very slow

I have the following query.
UPDATE t
SET UnitsSold = sub.UnitsSold,
FROM dbo.table1 t
JOIN (SELECT s.CustomerKey,
s.WeekKey,
s.ProductKey,
Sum(s.UnitsSold) AS [UnitsSold],
FROM dbo.table2 s
WHERE WeekKey >= 335
GROUP BY s.WeekKey,
s.CustomerKey,
s.ProductKey) AS sub
ON sub.WeekKey = t.WeekKey
AND sub.CustomerKey = t.CustomerKey
AND sub.ProductKey = t.ProductKey
It runs like a champ. About 2 seconds. Then when try and make it dynamic via the following.
DECLARE #StartWeekKey AS INT
SET #StartWeekKey = 335
UPDATE t
SET UnitsSold = sub.UnitsSold,
FROM dbo.table1 t
JOIN (SELECT s.CustomerKey,
s.WeekKey,
s.ProductKey,
Sum(s.UnitsSold) AS [UnitsSold],
FROM dbo.table2 s
WHERE WeekKey >= #StartWeekKey
GROUP BY s.WeekKey,
s.CustomerKey,
s.ProductKey) AS sub
ON sub.WeekKey = t.WeekKey
AND sub.CustomerKey = t.CustomerKey
AND sub.ProductKey = t.ProductKey
All of a sudden, it's super slow.
any good ideas?
EDIT:
Probalby should have mentioned this, but this is contained in a stored proc.
Added the #StartWeekKey as a parameter to the proc and it goes back to running in a few seconds.
This question seems to have been asked several times before and the general answer is that it has to do with statistics.
Try:
UPDATE STATISTICS table_or_indexed_view_name
to get your statistics up to date and see if that makes a difference.
That isn't unheard of when different parameters have very different distributions, thus different good plans. What can happen is that the query gets executed for a given value, and then that plan gets cached and re-used inappropriately for a different value.
If this is the case (just a guess - I can't run your query to check!) then try adding:
OPTION (OPTIMIZE FOR (#StartWeekKey UNKNOWN))
to the end of the query.
Another thought: is WeekKey actually an int ? is this some kind of mass type conversion issue?
I have no way of checking these; if I'm miles off the track, let me know so I can remove an unhelpful answer.

How can I display count of imagefield images in views?

I want to display the number of images uploaded to an imagefield, in a views field or views tpl.php. How can I do this? My imagefield is called boatimages. I tried this but it comes out as 0, not the correct number: < ? php print count($fields->field_boatimages) ?>
Ack. I do not think count() works like that.
Why not just do this using Views? Take a look at Arguments > Settings and you'll see 'display record count' which seems like all you would need for this.
My suggestion is install the devel module and use the function dpm to print the variable if you wanna know the structure (print_r() may work too). If count isn't working it's because, you are probably using it with the wrong data.
OR, you could just query the database for the field. I'm gonna provide you instructions for drupal 7 but drupal 6 should be similar.
Check the table field_data_field_boatimages. See how there's a list of your images related with a single entity_id
Then execute this query
SELECT COUNT(*) FROM `field_data_field_boatimages` WHERE entity_id = ###
Where ### is the entity_id you want to know. You can get it by looking for arg(1) if arg(0) == node in your page.
Now you just have to use php power to print thar result
$query = SELECT COUNT(*) FROM `field_data_field_boatimages` WHERE entity_id = :eid
$result = db_query($query, array(':eid', $nid))->fetchField();
echo $result;
Drupal 6 would be very similar. Just a little difference in the table names and the query syntax. For example using db_result instead of fetchField()
Anyway good luck!