Optional find() parameter in MongoDB when searching for values - mongodb

Basically what I am trying to do is say to my query that I want all of the users that have isBoosted = True to be first and after that, all others.
Thank You!

you can use the method sort to order descending because true=1 and false=0 like this:
db.users.find().sort("isBoosted", -1)
Or
db.users.find([your filter criteria]).sort("isBoosted", -1)

Related

Can't use changeable field in Mongoose Sort

Hello i want to use Mongoose sort but i have a problem when i want to change my sorting with arguments it doesn't work. For example
Users.find().sort({sortBy: 1})
Its not working at all. Whats the problem??
You have 2 problems in your code:
1. You are not specifying what field to sort by:
You forgot to change the sortBy field in your sort object to the wanted field to sort by.
For example, if you want to sort your users by name it will look like:
User.find().sort({name: 1})
2. You are not executing your query
You need to execute the query using the .exec(callback) function.
Your code will look like:
Users.find().sort({sortBy: 1}).exec((err, documents) => {
// Your logic
})
You can also use the await keyword to get your data without a callback function.
const users = await Users.find().sort({sortBy: 1}).exec();
Just note that if you decide to use the await option it needs to be in an async function.

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

Insert array during mongo insert [duplicate]

there are some questions here regarding how to save a result from a query into a javascript varialbe, but I'm just not able to implement them. The point is that I have a much difficult query, so this question is, in my opinion, unique.
Here is the problem. I have a collection namend "drives" and a key named "driveDate". I need to save 1 variable with the smallest date, and other with the biggest date.
The query for the smallest date is:
> db.drives.find({},{"_id":0,"driveDate":1}).sort({"driveDate":1}).limit(1)
The result is:
{ "driveDate" : ISODate("2012-01-11T17:24:12.676Z") }
how dan I save this to a variable, can I do something like:
tmp = db.drives.find({},{"_id":0,"driveDate":1}).sort({"driveDate":1}).limit(1)
Thanks!!!
Assuming you're trying to do this in the shell:
tmp = db.drives.find({}, {_id:0, driveDate:1}).sort({driveDate:1}).limit(1).toArray()[0]
find returns a cursor that you need to iterate over to retrieve the actual documents. Calling toArray on the cursor converts it to an array of docs.
After some time figuring out, I got the solution. here it is, for future reference:
var cursor = db.drives.find({},{"_id":1}).sort({"driveDate":1}).limit(1)
Then I can get the document from the cursor like this
var myDate = cursor.next()
That's it. Thanks for your help

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))" );

How to compare 2 mongodb collections?

Im trying to 'compare' all documents between 2 collections, which will return true only and if only all documents inside 2 collections are exactly equal.
I've been searching for the methods on the collection, but couldnt find one that can do this.
I experimented something like these in the mongo shell, but not working as i expected :
db.test1 == db.test2
or
db.test1.to_json() == db.test2.to_json()
Please share your thoughts ! Thank you.
You can try using mongodb eval combined with your custom equals function, something like this.
Your methods don't work because in the first case you are comparing object references, which are not the same. In the second case, there is no guarantee that to_json will generate the same string even for the objects that are the same.
Instead, try something like this:
var compareCollections = function(){
db.test1.find().forEach(function(obj1){
db.test2.find({/*if you know some properties, you can put them here...if don't, leave this empty*/}).forEach(function(obj2){
var equals = function(o1, o2){
// here goes some compare code...modified from the SO link you have in the answer.
};
if(equals(ob1, obj2)){
// Do what you want to do
}
});
});
};
db.eval(compareCollections);
With db.eval you ensure that code will be executed on the database server side, without fetching collections to the client.