I am getting confused with mongomapper + sorting.
I have a test blog with data with posts like this:
http://www.mongodb.org/display/DOCS/Schema+Design
Now, I would like to show just comments sorted by time asc for each blog entry.
If I use where, I get Plucky, when I use all() I get Array...how does this work?
The answer you linked to is sorting your result set in memory, which is expensive and likely going to cause errors if you have more comments than you can display in one batch.
The right way to sort this is using plucky's sort() method on the query, by created_at, descending (newest first):
post.comments.sort(:created_at).each {|comment| do_awesome_stuff(comment) }
(assuming you have a Post model that has_many comments and you're using the built-in created_at field on the comments for time.
Mongomapper uses a chaining query/filter model like ActiveRecord's scopes, which is why where() returns a chain-able Plucky query, as does sort(). You can then convert that into an array of results or chain more sorts/filters. You can also use enumerators like each() directly on the plucky query.
The code in the example above is doing the following chained calls:
Return a plucky query filtering all comments for this post object
Update that query to sort the comments returned by created_at, descending
Fetch a group of results from the db, and yield them to your code via each()
Related
What's the difference between:
DB::table('some_table')
->selectRaw('COUNT(*) AS result')
->get();
and:
DB::select(DB::raw("
SELECT COUNT(*) AS result
FROM some_table"));
In the documentation https://laravel.com/docs/5.6/queries they advert about using raw()due SQL Injection, but it's the same with selectRaw?
The end result of both is the same i.e but there are some difference:
The first one:
DB::table('some_table')
->selectRaw('COUNT(*) AS result')
->get();
Returns a collection of PHP objects,
You can call collections method fluently on the result
It is cleaner.
While the second:
DB::select(DB::raw("
SELECT COUNT(*) AS result
FROM some_table"
));
Returns an array of Php object.
Although they have similarities: the raw query string.
Those two examples yield the same result, although with different result data types.
Using raw queries can indeed be an attack vector if you don't escape values used within the query (especially those coming from user input).
However that can be mitigated very easily by using bindings passed as the second parameter of any raw query method, as showcased in the same documentation (selectRaw accepts a second parameter as an array of bindings, as well as other raw methods from the Query Builder such as whereRaw, etc). Actually at the begining of the docs page you referenced, the second paragraph also states the following:
The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
So as long as you're careful and make sure any parameters are passed as bindings and not concatenated as plain values within the raw query string you should be safe.
I am writing a cypher query in neo4j that merge few seperate queries with'UNION' operator. Now, the final result need to be sorted according to a specific column and I also need to be able to use 'LIMIT' to the final result so that I can fetch based on pagination request.
How to achieve that? adding 'ORDER BY' or 'LIMIT' at the end doesn't seems to work. Can't find a way to wrap the result as temporary set(as in sql queries) either. Any suggestions?
Currently it is not possible to add a ORDER BY or SKIP/LIMIT clause to the global set of UNION.
This is a pending feature request, see https://github.com/neo4j/neo4j/issues/2725
Maybe you can share your query and we can find a way to do it without UNION ?
eI need to select a particular single data element from first row ordered descending by date. Please specify the differences between the following keywords.
First
FirstOrDefault
singleOrDefault
Also need the precedence/order and usage rules of placing Orderby, where & select in Linq ORM Query. It would be much helpful if answer could be clear & descriptive.
Thanks in advance
A quick Google gives you the following Questions which address your question:
When to use .First and when to use .FirstOrDefault with LINQ?
LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria
You might also find the following article useful as it goes into each method:
http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/
As stated in the answers, the names do give it away (to those familiar), but here's a quick overview:
First
Will return the first entry in a collection (one or more results returned), will throw an exception if no records returned.
FirstOrDefault
Will return the first entry in a collection (one or more results returned), will return the appropriate default object if no records returned
SingleOrDefault
This one isn't really the same as the previously mentioned functions, it will return the result only if only one record is returned, otherwise will return the appropriate default object.
I tend to use First if I know that my results will always return "something", I use FirstOrDefault when I just want the first element but know that sometimes the query might return nothing. I've yet to personally use SingleOrDefault but it should only be used where your query is only ever going to return one row and that returned results should be ignored if more than one result exists.
We're running Solr 3.6 and are trying to apply a conditional sort on the result set. To clarify, the data is a set of bids, and we want to add the option to sort by the current user's bid, so it can't function as a regular sort (as the bid will be different for each user that runs the query).
The documents in the result set include a "CurrentUserId" and "CurrentBid" field, so I think we need something like the following to sort:
sort=((CurrentUserId = 12345) ? CurrentBid : 0) desc
This is just pseudocode, but the idea is that if the currentUserId in Solr matches the user Id (12345 in this example), then sort by CurrentBid, otherwise, just use 0.
It seems like doing a sort by query might be the way to go with achieving this (or at least form part of the solution), using something like the following query:
http://localhost:8080/solr/select/?q=:&sort=query(CurrentUserId:10330 AND CurrentBid:[1 TO *])+desc
This doesn't seem to be working for me though, and results in the following error:
sort param could not be parsed as a query, and is not a field that exists in the index: ...
The Solr documentation indicates that the query function can be used as a sort parameter from Solr 1.4 onwards, so this seems like it should work.
Any advice on how to go about achieving this would be greatly appreciated.
According to the Solr Documentation link you provided,
Any type of subquery is supported through either parameter dereferencing $otherparam or direct specification of the query string in the LocalParams via "v".
So based on the examples and your query, I think one or both of the following should work:
http://localhost:8080/solr/select/?q=:&sort=query($qq)+desc&qq=(CurrentUserId:10330 AND CurrentBid:[1 TO *])
http://localhost:8080/solr/select/?q=:&sort=query({v='CurrentUserId:10330 AND CurrentBid:[1 TO *]'})+desc
I am quite sure that DQL will be the way to go, but I am wondering if Doctrine, i am using Doctrine 2, has someway to return the row count. I won't be using the rows itself, I just want the count.
I'm new to Doctrine2 but it looks like you can simply do this:
$query = $em->createQuery('SELECT COUNT(u.id) FROM Entities\User u');
$count = $query->getSingleScalarResult();
Source (Using Agregate Functions): http://www.doctrine-project.org/docs/orm/2.0/en/reference/dql-doctrine-query-language.html#dql-select-examples
Allowed aggregate functions: http://www.doctrine-project.org/docs/orm/2.0/en/reference/dql-doctrine-query-language.html#aggregate-functions
Here is another interesting point of view about using aggregated functions in DQL
http://doctrine-orm.readthedocs.org/en/latest/cookbook/aggregate-fields.html
Maybe you would avoid the creation of an specific query to obtain an aggregate value. In this case, aggregate fields are a good alternative.