I have a very basic question:
SELECT name, surname CONCAT(name, surname) AS name_surname from users;
How can I convert this SQL to MongoDB query?
During my search, I have decided that it is possible with aggregate framework due to concat, but what I received is only projection of concat(name, surname) not name, surname and concat(name, surname).
Final thing I got is this query:
db.inroamers.find().forEach(
function(o) {
print(o.LAC + '-' + o.CELL + ' ' + o.CHARGE + ' ' + o.WEEK);
})
but it does not give me proper json array.
Any suggestions?
Use the aggregation operations as below:
db.collection.aggregate([
{$project:{"name_surname":{$concat:["$name","-","$surname"]},"name":1,"surname":1}}
])
Related
How can I access column's from SELECT, in my WHERE statement? I'm probably missing quotes. For context, this is in a controller, in Strapi CMS, which runs on a node.js server.
Problem:
Occurs at AND statement (mainly the first st_geomfromtext line):
const rawBuilder = strapi.connections.default.raw(
`
SELECT
locations.id as Location_ID,
locations.Title as Location_Title,
locations.Latitude as Location_Latitude,
locations.Longitude as Location_Longitude,
things.id,
things.Title,
things.Location
FROM locations
RIGHT JOIN things
ON locations.id = things.Location
WHERE things.Style = ` + ctx.query['Style.id'] + `
AND round(st_distance_sphere(
st_geomfromtext(CONCAT('POINT(',locations.Longitude, ' ', locations.Latitude,')')),
st_geomfromtext(CONCAT('POINT(` + ctx.query.Longitude + ` ` + ctx.query.Latitude + `)'))
)) <= ` + 5000
)
Test works:
Just for fun, same as above, but just passed request variables for both st_geomfromtext lines, and the response works; no SQL error:
AND round(st_distance_sphere(
st_geomfromtext(CONCAT('POINT(` + ctx.query.Longitude1 + ` ` + ctx.query.Latitude1 + `)')),
st_geomfromtext(CONCAT('POINT(` + ctx.query.Longitude2 + ` ` + ctx.query.Latitude2 + `)'))
)) <= ` + 5000
So as far as I can tell, the first st_geomfromtext line is the culprit, however it (the 1st line) works fine in a Go server... another clue that this is just a syntax problem.
Below is a working example in SQL Server that should help you resolve this.
Please try these steps:
Remove the "AND" statement from your where clause and save it somewhere
Add some filter criteria that will give you just few known locations
Add new output fields in your select criteria for each function so you will know what you are comparing.
Select CONCAT('POINT(',locations.Longitude, ' ', locations.Latitude,')') from locations
Select st_geomfromtext(CONCAT('POINT(',locations.Longitude, ' ', locations.Latitude,')')) from locations
Note: the output to the geo functions this will probably look cryptic like 0xE6100000010C75931804564253C042CF66D5E7724340
Once the values line up the way you expect then add a new version of the where clause with the adjustments you have made.
Check the precision of the st_distance_sphere function. In SQL Server this is defaulted to meters.
Example in SQL Server
CREATE TABLE #locations (id INT, Title VARCHAR(50), Latitude DECIMAL(10,4), Longitude DECIMAL(10,4))
CREATE TABLE #things (id INT, Title VARCHAR(50), LocationId INT)
INSERT INTO #locations (id, Title, Latitude, Longitude) Values (1,'WH', 38.8977, -77.0365)
INSERT INTO #locations (id, Title, Latitude, Longitude) Values (2,'CB', 38.8899, -77.0091)
INSERT INTO #things (id, Title, LocationId) Values (100,'White House',1)
INSERT INTO #things (id, Title, LocationId) Values (101,'United States Capitol',2)
--My Location at the Washington Monument
DECLARE #myLat DECIMAL(10,4) = 38.8895;
DECLARE #myLong DECIMAL(10,4) = -77.0353
SELECT
loc.id as Location_ID,
loc.Title as Location_Title,
loc.Latitude as Location_Latitude,
loc.Longitude as Location_Longitude,
th.id,
th.Title,
th.LocationId,
geometry::STGeomFromText(CONCAT('POINT(',loc.Longitude, ' ', loc.Latitude,')'),4326) as ItemPoint,
geometry::STGeomFromText(CONCAT('POINT(',#myLat,' ',#myLong,')'),4326) as MyPoint,
geometry::STGeomFromText(CONCAT('POINT(',loc.Longitude, ' ', loc.Latitude,')'),4326).STDistance(geometry::STGeomFromText(CONCAT('POINT(',#myLat,' ',#myLong,')'),4326))
FROM #locations loc
RIGHT JOIN #things th ON loc.id = th.LocationId
DROP TABLE #locations
DROP TABLE #things
i have a select query to a local database and for some reason the following error shows up:
ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'FROM site WHERE name = OCC AND date_start = 2018-07-30 08:00:00 AND date_end = '' at line 1
here's my query:
connection.query("SELECT *, FROM shop WHERE name = " + shop_name + " AND date_start = " + myDate + " AND date_end = " + myDate2, function (err, result)
{
if (err)
{
console.log("Error Is:" + err);
}
else
{
console.log('DATA EXISTING IS =' + JSON.stringify(result));
}
});
am i missing something?
The usual mantra: use parameterized queries. They will prevent SQL injections and make your service more secure. Furthermore they will take care of the usual pitfalls when building a query using string concatenation.
Let's have a look at your query
"SELECT *, FROM shop WHERE name = " + shop_name + " AND date_start = " + myDate + " AND date_end = " + myDate2
Which spells out to something like
SELECT *, FROM shop WHERE name = myshop AND date_start = 2018-07-30 AND date_end = 2018-08-10
There are at least 3 errors
The , behind the SELECT * this is also the one the error tells you about. I suppose you had a column list and replaced it with *
The shop name column is most certainly some char column. So you have to enclose your values with quotes
Also the dates must be used with quotes, so the SQL engine will parse it to a date and do the comparison. For some SQL engines there is also a special annotation for dates. Have a look in the documentation.
This query should work
"SELECT * FROM shop WHERE name = '" + shop_name + "' AND date_start = '" + myDate + "' AND date_end = '" + myDate2 +"'"
depending on what myDate and myDate2 are.
At least problems 2 and 3 would not happen if you use parameterized queries. Consult the documentation of the library you are using.
I'm trying to insert values using mysql in nodejs. I had written the following code and installed MySQL support via npm,But canot to INSERT INTO the table due to this problem.
My code;
var mysql = require('mysql');
var values=randomValueHex(8);
var sql = "INSERT INTO `activationkeys`(`activationKey`, `productId`)
VALUES ( values ,'3')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
My Error on terminal:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''3')'
How can i solve this problem?
Why are you using back quote for the column names? We do not need that in column names. You can simply create your dynamic sql query by using + operator on the column values like this:
var sql = "INSERT INTO activationkeys (activationKey, productId) VALUES ( " + values + " ,'3')";
Instead of
var sql = "INSERT INTO `activationkeys`(`activationKey`, `productId`)
VALUES ( values ,'3')";
Please try this
var sql = "INSERT INTO `activationkeys`(`activationKey`, `productId`)
VALUES ( " + values + " ,'3')";
provided values is a string
values currently means nothing the way you're using it in the SQL query.
What is values? Is it an integer, or a string?
Nevertheless, you need to concatenate the values variable within the string.
var sql = "INSERT INTO `activationkeys`(`activationKey`, `productId`) VALUES (" + values + ",'3')";
And one more correction values variable have to give like this '" + values + "' . This is the most correct way of define as a variables. Otherwise you give like this " + values + " , you may be have an error accure like this Error: ER_BAD_FIELD_ERROR: Unknown column 'xxxxxx' in 'field list'. And my code is
var sql = "INSERT INTO `activationkeys`(`activationKey`, `productId`) VALUES ( '" + values + "' , 3 )";
This is simple way to write SQL query in you JavaScript code.
Try It Once
const QUERY = INSERT INTO users (firstName, lastName) VALUES ( "${firstName}", "${lastName}")
Note: Please wrap your complete query into the back ticks.
I have a bot that is built with botkit and using a Zendesk api to pull information.
I have a function that asks a user for a search term and the bot searches relevant information about that search term. It pulls the information from the Zendesk API and outputs the answer.
I don't understand when accessing the object's value some values are able to be outputted while some are not.
For example, if the user submits 'jim' as the search term. I can pull relevant information by doing this: tickets[0].id + tickets[0].priority + tickets[0].subject + tickets[0].description.
When I do something like this:
tickets[4]- I get undefined values.
The full code of what I'm trying to do is this:
controller.hears(['SEARCH TICKET',/search ticket/gi, /^.{0,}jirabot.
{0,}$/],
['direct_message','direct_mention','mention','ambient'],function(bot,message)
{
// start a conversation to handle this response.
bot.startConversation(message,function(err,convo) {
convo.ask('What are you looking for?',function(response,convo) {
zendesk.search.list('query='+response.text+'&sort_by=priority&sort_order=desc').then(function(tickets){
console.log(tickets);
bot.reply(message, 'The Ticket ID Number: ' + tickets[3] + tickets[0].id + '\n The Ticket Priority: ' + tickets[0].priority + '\n The Ticket Subject: ' + tickets[0].subject + '\n The Ticket Description: \n'+ tickets[0].description + '\n');
convo.next();
}
});
});
});
});
Here is what the JSON looks like:
{
"results": [(in here is the information like ticket subject, priority, id,
etc.],
"facets": null,
"next_page": null,
"previous_page": null,
"count": 2
}
How do I get the value for count? I get undefined when I do tickets[4].
To access the properties of the JSON you've shown, you wouldn't use index values like 0,1,2,3. Instead you'd write ticket["results"], ticket["count"], ticket["<PropNameHere>"]
I have a string that has a query.
The problem is I cannot just append to it, after the where clause there is a group by.
So say i'm given this string:
var query = "select stuff from db where something = 3 group by stuff"
Now I want to append "somethingelse > 5 AND "
Result:
query = "select stuff from db where somethingelse > 5 AND something = 3 group by stuff"
What do I need to do to do this? Thanks
query = query.replace(/where/,'where somethingelse > 5 AND');
David's answer is the most pragmatic if you are passed the query string as-is.
Alternatively, if you're building it up yourself it may be better to allow the list of selectors, query constraints etc. to be passed in so that you create a correct query string initially. Something a bit like:
val query = "select " + selectors.join() +
" from " + tables.join() +
" where " + constraints.join() +
" group by " + groupings.join()