How to convert SQL query to MongoDB - sql

SELECT s_name FROM supplier
WHERE s_suppkey = ALL
(SELECT s_suppkey FROM supplier
WHERE s_nationkey > 50 AND s_acctbal= 9658.99 )
I don't know how to do this part
WHERE s_suppkey = ALL
(SELECT s_suppkey FROM supplier
WHERE s_nationkey > 50 AND s_acctbal= 9658.99 )

db.supplier.find( {}, { $and : [ { s_nationkey : { '$gt' : 50 } }, { s_acctbal : 9658.99 } ] } ,{s_suppkey:1} )
But does not return suppliers name!

You SQL looks a bit strange. For Mongo try this one:
db.supplier.find({ s_nationkey: { '$gt': 50 }, s_acctbal: 9658.99 }, {s_name :1} )

Related

Sum of column values ​inside Json array with group by

I have next Django model.
class StocksHistory(models.Model):
wh_data = models.JsonField()
created_at = models.DateTimeField()
I store JSON data in wh_data.
[
{
"id":4124124,
"stocks":[
{
"wh":507,
"qty":2
},
{
"wh":2737,
"qty":1
}
],
},
{
"id":746457457,
"stocks":[
{
"wh":507,
"qty":3
}
]
}
]
Note: it's data for one row - 2022-06-06.
I need to calculate the sum inside stocks by grouping them by wh and by created_at so that the output is something like this
[
{
"wh":507,
"qty":5,
"created_at":"2022-06-06"
},
{
"wh":2737,
"qty":1,
"created_at":"2022-06-06"
},
{
"wh":507,
"qty":0,
"created_at":"2022-06-07"
},
{
"wh":2737,
"qty":2,
"created_at":"2022-06-07"
}
]
I know how to group by date, but I don't understand how to proceed with aggregations inside JsonField.
StocksHistory.objects.extra(select={'day': 'date( created_at )'})
.values('day')
.annotate(
???
)
A solution is suitable, both through Django ORM and through RAW SQL.
demo
WITH cte AS (
SELECT
jsonb_path_query(js, '$[*].stocks.wh')::numeric AS wh,
jsonb_path_query(js, '$[*].stocks.qty')::numeric AS b,
_date
FROM (
VALUES ('[
{
"id":4124124,
"stocks":[
{
"wh":507,
"qty":2
},
{
"wh":2737,
"qty":1
}
]
},
{
"id":746457457,
"stocks":[
{
"wh":507,
"qty":3
}
]
}
]'::jsonb)) v (js),
(
VALUES ('2022-06-06'), ('2022-06-07')) ss_ (_date)
),
cte2 AS (
SELECT
wh, sum(b) AS qty,
_date
FROM
cte
GROUP BY
1,
3
ORDER BY
1
)
SELECT
array_agg(row_to_json(cte2.*)::jsonb)
FROM
cte2;

Convert Sql to MonogoDb

how can i write this sql in monogb query
select distinct(Users.id)
,userName,gender
,displayPic
,dob
,aboutUser
,jobTitle
,company
,school
,dontShowAge
,makeDistanceInvisible
, isUserVerified
, (DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(dob, '%Y')) as age
, ( 6371 * acos ( cos ( radians(?) ) * cos( radians( locLattitude ) ) * cos( radians( locLongitude ) - radians(?) ) + sin ( radians(?) ) * sin( radians( locLattitude ) ) ) ) as distance,religion.religion_name
FROM Users
INNER JOIN religion
ON(Users.religion = religion.id)
WHERE Users.displayPic <> 'NULL'
AND gender = ?
AND showMeTinder = '1'
AND Users.id <> ?
AND ( (
select count(pairID)
from Swipe
where senderID = ?
AND receiverID = Users.id) = 0
AND ( ( select count(pairID) from Swipe where receiverID = ?
AND senderID = Users.id
AND NOT (swipeType = 'like' OR 'superlike') ) = 0 ) )
LIMIT 10
Here is the MongoDB code I wrote
let aggregate = [
{ $match: { userID: { $ne: data.userID }, userName: { $ne: "" }, userName: { $ne: undefined } } },
{ $sort: { _id: -1 } },
{
$project: {
_id: 0, userID: 1, pairid : {
$cond: { if: { $gte: ["$userID", data.userID] }, then: { $concat: [ data.userID, "$userID" ] }, else: { $concat: [ "$userID", data.userID, ] } }
}
}
},
{
$lookup:
{
from: swipeCollection,
localField: 'pairid',
foreignField: "pairID",
as: "data"
}
},
{ $unwind: "$data" },
{
$project: {
_id: 0, userID : 1, "data.swipeType": 1,
}
},
{ $limit: 3 },
]
the issue here is that it return swipe data
what am trying to solve is get data from user collection then check it in swipe collections then return the combination of both user and swipe and the user collection data might not be present in swipe
Thanks

How to create a multi-level json output using sql query in SQL Server 2016?

Is that possible create a multi-level json string in SQL Server 2016 ? I have a table (patient_data) like this:
And what i want to do is to create json string output in SQL Server like this:
{
"patient":[
{
"key":"A",
"data":[
{
"name":"Amy Farha",
"colored":"darkred",
"avatar_url":"https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg",
"subtitle":"Vice President",
"patientid":"qweqweqeqeq"
},
{
"name":"Anies",
"colored":"darkblue",
"avatar_url":"https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg",
"subtitle":"Vice Chairman",
"patientid":"avasdasdad"
}
]
},
{
"key":"B",
"data":[
{
"name":"Bryan Adams",
"colored":"darkgreen",
"avatar_url":"https://randomuser.me/api/portraits/med/women/91.jpg",
"subtitle":"Reggae Man",
"patientid":"avasdasdad"
}
]
},
{
"key":"D",
"data":[
{
"name":"David dummy",
"colored":"darkgreen",
"avatar_url":"https://randomuser.me/api/portraits/med/women/91.jpg",
"subtitle":"Reggae Man",
"patientid":"avasdasdad"
}
]
},
{
"key":"M",
"data":[
{
"name":"Muhammad Adams",
"colored":"darkgreen",
"avatar_url":"https://randomuser.me/api/portraits/med/women/91.jpg",
"subtitle":"Reggae Man",
"patientid":"avasdasdad"
}
]
},
{
"key":"T",
"data":[
{
"name":"Tere",
"colored":"darkgreen",
"avatar_url":"https://randomuser.me/api/portraits/med/women/91.jpg",
"subtitle":"Reggae Man",
"patientid":"avasdasdad"
},
{
"name":"Tifanny",
"colored":"darkblue",
"avatar_url":"https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg",
"subtitle":"Vice Chairman",
"patientid":"avasdasdad"
}
]
},
{
"key":"X",
"data":[
{
"name":"Xavier",
"colored":"darkgreen",
"avatar_url":"https://randomuser.me/api/portraits/med/women/91.jpg",
"subtitle":"Reggae Man",
"patientid":"avasdasdad"
}
]
}
]
}
**NOTE "key" is a grouping by the first letter of patient's name
I try use json path but couldn't figure out in multi level case .I hope someone can help me
Try the following queries with FOR JSON PATH
-- test data
CREATE TABLE Patients(
id int,
name varchar(100)
)
INSERT Patients(id,name)VALUES
(11,'A Patient 11'),(12,'A Patient 12'),
(21,'B Patient 21'),
(31,'C Patient 31'),(32,'C Patient 32')
-- query 1
SELECT
(
SELECT
k.[key],
(SELECT p.id,p.[name] FROM Patients p WHERE LEFT(p.[name],1)=k.[key] FOR JSON PATH) [data]
FROM
(
SELECT DISTINCT LEFT([name],1) [key]
FROM Patients
) k
ORDER BY k.[key]
FOR JSON PATH
) patient
FOR JSON PATH
/*
[
{"patient":[
{"key":"A","data":[{"id":11,"name":"A Patient 11"},{"id":12,"name":"A Patient 12"}]},
{"key":"B","data":[{"id":21,"name":"B Patient 21"}]},
{"key":"C","data":[{"id":31,"name":"C Patient 31"},{"id":32,"name":"C Patient 32"}]}
]
}
]
*/
-- query 2
SELECT
k.[key] [patient.key],
(SELECT p.id,p.[name] FROM Patients p WHERE LEFT(p.[name],1)=k.[key] FOR JSON PATH) [patient.data]
FROM
(
SELECT DISTINCT LEFT([name],1) [key]
FROM Patients
) k
ORDER BY k.[key]
FOR JSON PATH
/*
[
{"patient":{"key":"A","data":[{"id":11,"name":"A Patient 11"},{"id":12,"name":"A Patient 12"}]}},
{"patient":{"key":"B","data":[{"id":21,"name":"B Patient 21"}]}},
{"patient":{"key":"C","data":[{"id":31,"name":"C Patient 31"},{"id":32,"name":"C Patient 32"}]}}
]
*/
You can append WITHOUT_ARRAY_WRAPPER to remove the brackets [ and ]
SELECT
(
SELECT
k.[key],
(SELECT p.id,p.[name] FROM Patients p WHERE LEFT(p.[name],1)=k.[key] FOR JSON PATH) [data]
FROM
(
SELECT DISTINCT LEFT([name],1) [key]
FROM Patients
) k
ORDER BY k.[key]
FOR JSON PATH
) patient
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
/*
{
"patient":[
{"key":"A","data":[{"id":11,"name":"A Patient 11"},{"id":12,"name":"A Patient 12"}]},
{"key":"B","data":[{"id":21,"name":"B Patient 21"}]},
{"key":"C","data":[{"id":31,"name":"C Patient 31"},{"id":32,"name":"C Patient 32"}]}
]
}
*/
I found another more shorter variant. You can use ROOT('patient') option here
SELECT
k.[key] [key],
(SELECT p.id,p.[name] FROM Patients p WHERE LEFT(p.[name],1)=k.[key] FOR JSON PATH) [data]
FROM
(
SELECT DISTINCT LEFT([name],1) [key]
FROM Patients
) k
ORDER BY k.[key]
FOR JSON PATH, ROOT('patient')
/*
{
"patient":[
{"key":"A","data":[{"id":11,"name":"A Patient 11"},{"id":12,"name":"A Patient 12"}]},
{"key":"B","data":[{"id":21,"name":"B Patient 21"}]},
{"key":"C","data":[{"id":31,"name":"C Patient 31"},{"id":32,"name":"C Patient 32"}]}
]
}
*/

MDX: Query Data analysed

In this query i used were clause in that year is 2015 and quarter-[2013]&[Quarter1], how is it possible, and getting result set 10 records. actually result set is not displaying.
WITH MEMBER [Measures].[Test] AS ( [Measures].[ProgramAssessmentPatientCnt] + [Measures].[AssessmentPatientCnt] )
MEMBER [Measures].[Test1] AS ( [Measures].[CCMPatientCnt] + [Measures].[CareteamCnt] + [Measures].[CCMPatientCnt] )
SELECT ( ( { [DimEnrollStatus].[EnrollmentStatus].[EnrollmentStatus] } ),
{ [Measures].[AssessmentPatientCnt], [Measures].[Test], [Measures].[Test1] } ) ON COLUMNS,
Subset (
NonEmpty (
{
( { [DimAssessment].[AssessmentText].[AssessmentText] },
{ [DimAssessment].[QuestionText].[QuestionText] },
{ [DimAssessment].[AnswerText].[AnswerText] } )
},
{ [Measures].[AssessmentPatientCnt], [Measures].[Test], [Measures].[Test1] }
),
0,
10
) ON ROWS
FROM [NavigateCube]
WHERE (
{
( { [DimManagedPopulation].[ManagedPopulationName].&[1044]&[LTC Lincoln Centers] },
{ [DimAnchorDate].[Calender Year].&[2015] },
{ [DimAnchorDate].[Calendar Semester Des].[All] },
{ [DimAnchorDate].[Calendar Quarter Des].&[2013]&[Quarter1] },
{ [DimAnchorDate].[English Month Name Desc].[All] } )
} )
Does this return any rows?
WHERE
(
[DimManagedPopulation].[ManagedPopulationName].&[1044]&[LTC Lincoln Centers],
[DimAnchorDate].[Calender Year].&[2015],
//[DimAnchorDate].[Calendar Semester Des].[All],
[DimAnchorDate].[Calendar Quarter Des].&[2013]&[Quarter1],
[DimAnchorDate].[English Month Name Desc].[All]
);
Maybe the following:
WHERE
(
[DimManagedPopulation].[ManagedPopulationName].&[1044]&[LTC Lincoln Centers],
{
[DimAnchorDate].[Calender Year].&[2015],
[DimAnchorDate].[Calendar Semester Des].[All],
[DimAnchorDate].[Calendar Quarter Des].&[2013]&[Quarter1],
[DimAnchorDate].[English Month Name Desc].[All]
}
);

sql to mongodb translation

I wonder how we can do the below translation from sql to mongoDB:
Assume the table has below structure:
table
=====
-----
##id contribution time
1 300 Jan 2, 1990
2 1000 March 3, 1991
And I want to find a ranking list of ids in the descending orders of their number of contributions.
'$' This is what I do using sql:
select id, count(*) c from table group by id order by c desc;
How can I translate this complex sql into mongoDB using count(), order() and group()?
Thank you very much!
Setting up test data with:
db.donors.insert({donorID:1,contribution:300,date:ISODate('1990-01-02')})
db.donors.insert({donorID:2,contribution:1000,date:ISODate('1991-03-03')})
db.donors.insert({donorID:1,contribution:900,date:ISODate('1992-01-02')})
You can use the new Aggregation Framework in MongoDB 2.2:
db.donors.aggregate(
{ $group: {
_id: "$donorID",
total: { $sum: "$contribution" },
donations: { $sum: 1 }
}},
{ $sort: {
donations: -1
}}
)
To produce the desired result:
{
"result" : [
{
"_id" : 1,
"total" : 1200,
"donations" : 2
},
{
"_id" : 2,
"total" : 1000,
"donations" : 1
}
],
"ok" : 1
}
Check the mongodb Aggregation
db.colection.group(
{key: { id:true},
reduce: function(obj,prev) { prev.sum += 1; },
initial: { sum: 0 }
});
After you get the result, sort it by sum.