how to get projections in mongodb with group operator - mysql

I have a table with columns Column1 & Column2 which looks like this
Colum1 Column2
A 1
A 2
A 3
B 2
B 4
B 6
If I perform following SQL in MYSQL
SELECT Column1, Column2, count(*) from Table group by Column1;
Result is
Column1 Column2 Count(*)
A 1 3
B 2 3
I want to execute similar query on MONGODB
I tried
QUERY1: db.table.aggregate({$group: {_id:"$Column1", count:{$sum:1}} })
QUERY2: db.table.aggregate({$project: {column1:1, column2:1}}, {$group: {_id:"$Column1", count:{$sum:1}} })
However the result for Query2 is same as Query1, It seems like you can not populate fields other than mentioned in $group column.
Is there a way to populate other fields in mongodb along with $group operator ?

I'm not sure I read the mysql query correctly, and I don't understand why this is particularly useful, but $first seems to accomplish the same thing.
However, as mentioned in the $first documentation, the outcome depends on the sorting so you should include a sorting criterion.
Data (column names shortened for brevity)
> db.foo.insert({"C1" : "A", "C2" : 1});
> db.foo.insert({"C1" : "A", "C2" : 2});
> db.foo.insert({"C1" : "A", "C2" : 3});
> db.foo.insert({"C1" : "B", "C2" : 2});
> db.foo.insert({"C1" : "B", "C2" : 4});
> db.foo.insert({"C1" : "B", "C2" : 6});
Aggregation Query
> db.foo.aggregate({$group: {_id:"$C1", C2: { $first: "$C2" }, count:{$sum:1}} })
Results
{
"result" : [
{
"_id" : "B",
"C2" : 2,
"count" : 3
},
{
"_id" : "A",
"C2" : 1,
"count" : 3
}
],
"ok" : 1
}

Related

Postgres Json List of Map

I have one sample json as below
{
"jsonObject":
[
{ "Name" : "XPerson",
"Age" : 18},
{ "Name" : "YPerson",
"Age" : 18}
]
}
I can have this list to N numbers. I want to separate this in different column based on Age like less than 18 in column1, between 18 to 25 in column2 and all other in column3.
How can we achieve in postgres?
It sounds like you are trying to do front end's job at database level.
with data(Age,Name) as
(select *
from jsonb_to_recordset(' {
"jsonObject": [
{
"Name": "XPerson",
"Age": 18
},
{
"Name": "YPerson",
"Age": 18
}
]
}'::jsonb -> 'jsonObject') as t("Age" int, "Name" text))
select
string_agg(case when age < 18 then name end,',') as Column1,
string_agg(case when age >= 18 and age <=25 then name end,',') as Column2,
string_agg(case when age > 25 then name end,',') as Column3
from data;

Delete value from nested json - postgres

I have the json block modeled below. I want to selectively delete individual blocks from my_items based on the id which is AAA and BBB in my sample. ie if I tried to delete the AAA block under my_items I would want tojust delete the {"id" : "AAA"} but if wanted to delete the BBB block it would delete the larger {"name" : "TestRZ", "id" : "BBB", "description" : ""} block.
I know I can use the #- to remove whole blocks like SELECT '{sample_json}'::jsonb #- '{my_items}' would purge out the whole my_items block. But I dont know how to use this to conditionally delete children under a parent block of json. I have also used code similar to this example to append data inside a nested structure by reading in the node of the nested structure cat-ing new data to it and rewriting it. UPDATE data SET value= jsonb_set(value, '{my_items}', value->'items' || (:'json_to_adds'), true) where id='testnofeed'.
But I dont know how to apply either of these methods to: 1)Delete data in nested structure using #- or 2)Do the same using `jsonb_set. Anyone have any guidance for how to do this using either of these(or another method).
{
"urlName" : "testurl",
"countryside" : "",
"description" : "",
"my_items" : [
{
"id" : "AAA"
},
{
"name" : "TestRZ",
"id" : "BBB",
"description" : ""
},
],
"name" : "TheName"
}
Data is stored in value jsonb. when I update I will be able to pass in a unique kind so that it only updates this json in one row in db.
-- Table Definition
CREATE TABLE "public"."data" (
"id" varchar(100) NOT NULL,
"kind" varchar(100) NOT NULL,
"revision" int4 NOT NULL,
"value" jsonb
);
This works in PostgreSQL 12 and later with jsonpath support. If you do not have jsonpath, then please leave a comment.
with data as (
select '{
"urlName" : "testurl",
"countryside" : "",
"description" : "",
"my_items" : [
{
"id" : "AAA"
},
{
"name" : "TestRZ",
"id" : "BBB",
"description" : ""
}
],
"name" : "TheName"
}'::jsonb as stuff
)
select jsonb_set(stuff, '{my_items}',
jsonb_path_query_array(stuff->'my_items', '$ ? (#."id" <> "AAA")'))
from data;
jsonb_set
---------------------------------------------------------------------------------------------------------------------------------------------------
{"name": "TheName", "urlName": "testurl", "my_items": [{"id": "BBB", "name": "TestRZ", "description": ""}], "countryside": "", "description": ""}
(1 row)
To update the table directly, the statement would be:
update data
set value = jsonb_set(value, '{my_items}',
jsonb_path_query_array(value->'my_items',
'$ ? (#."id" <> "AAA")'));
This works for versions before PostgreSQL 12:
with data as (
select 1 as id, '{
"urlName" : "testurl",
"countryside" : "",
"description" : "",
"my_items" : [
{
"id" : "AAA"
},
{
"name" : "TestRZ",
"id" : "BBB",
"description" : ""
}
],
"name" : "TheName"
}'::jsonb as stuff
), expand as (
select d.id, d.stuff, e.item, e.rn
from data d
cross join lateral jsonb_array_elements(stuff->'my_items') with ordinality as e(item, rn)
)
select id, jsonb_set(stuff, '{my_items}', jsonb_agg(item order by rn)) as new_stuff
from expand
where item->>'id' != 'AAA'
group by id, stuff;
id | new_stuff
----+---------------------------------------------------------------------------------------------------------------------------------------------------
1 | {"name": "TheName", "urlName": "testurl", "my_items": [{"id": "BBB", "name": "TestRZ", "description": ""}], "countryside": "", "description": ""}
(1 row)
The direct update for this is a little more involved:
with expand as (
select d.id, d.value, e.item, e.rn
from data d
cross join lateral jsonb_array_elements(value->'my_items')
with ordinality as e(item, rn)
), agg as (
select id, jsonb_set(value, '{my_items}', jsonb_agg(item order by rn)) as new_value
from expand
where item->>'id' != 'AAA'
group by id, value
)
update data
set value = agg.new_value
from agg
where agg.id = data.id;

Subset a JSON Object with MySQL Query

I have a MySQL database and one of the tables is called 'my_table'. In this table, one of the columns is called 'my_json_column' and this column is stored as a JSON object in MySQL. The JSON object has about 17 key:value pairs (see below). I simply want to return a "slimmed-down" JSON Object from a MySQL query that returns 4 of the 17 fields.
I have tried many different MySQL queries, see below, but I can't seem to get a returned subset JSON Object. I am sure it is simple, but I have been unsuccessful.
Something like this:
SELECT
json_extract(my_json_column, '$.X'),
json_extract(my_json_column, '$.Y'),
json_extract(my_json_column, '$.KB'),
json_extract(my_json_column, '$.Name')
FROM my_table;
yields:
5990.510000 90313.550000 5990.510000 "Operator 1"
I want to get this result instead (a returned JSON Object) with key value pairs:
[ { X: 5990.510000, Y: 90313.550, KB: 2105, Name: "Well 1" } ]
Sample data:
{
"Comment" : "No Comment",
"Country" : "USA",
"County" : "County 1",
"Field" : "Field 1",
"GroundElevation" : "5400",
"Identifier" : "11435358700000",
"Interpreter" : "Interpreter 1",
"KB" : 2105,
"Name" : "Well 1",
"Operator" : "Operator 1",
"Owner" : "me",
"SpudDate" : "NA",
"State" : "MI",
"Status" : "ACTIVE",
"TotalDepth" : 5678,
"X" : 5990.510000,
"Y" : 90313.550
}
Thank you in advance.
Use JSON_OBJECT(), available since MySQL 5.6:
Evaluates a (possibly empty) list of key-value pairs and returns a JSON object containing those pairs
SELECT
JSON_OBJECT(
'X', json_extract(my_json_column, '$.X'),
'Y', json_extract(my_json_column, '$.Y'),
'KB', json_extract(my_json_column, '$.KB'),
'Name', json_extract(my_json_column, '$.Name')
) my_new_json
FROM my_table;
This demo on DB Fiddle with your sample data returns:
| my_new_json |
| ----------------------------------------------------------- |
| {"X": 5990.51, "Y": 90313.55, "KB": 2105, "Name": "Well 1"} |

How select mysql with condition on nested array json?

i'm create a table have one json column and data of inserted has below structure:
{
"options" : {
"info" : [
{"data" : "data1", "verified" : 0},
{"data" : "data2", "verified" : 1},
... and more
],
"otherkeys" : "some data..."
}
}
i want to run a query to get data of verified = 1 "info"
this is for mysql 5.7 comunity running on windows 10
select id, (meta->"$.options.info[*].data") AS `data`
from tbl
WHERE meta->"$.options.info[*].verified" = 1
is expect the output of "data2" but the actual output is nothing.
below query worked perfectly
select id, (meta->"$.options.info[*].data") AS `data`
from tbl
WHERE meta->"$.options.info[1].verified" = 1
but i need to search all item in array not only index 1
how can fix it ?
(sorry for bad english)
Try:
SELECT `id`, (`meta` -> '$.options.info[*].data') `data`
FROM `tbl`
WHERE JSON_CONTAINS(`meta` -> '$.options.info[*].verified', '1');
See dbfiddle.

Separate single record into two rows by column names

I want to separate a single record into 2 records by their column names.
Consider only a single record for now.
Currently what I get using simple select query:
{ "id" : "1", "route_name" : "6", "start_up" : "Mumbai", "destination_up" : "Delhi", "start_down" : "Delhi", "destination_down" : "Mumbai" }
What I actually need:
{ "id" : "1", "route_name" : "6", "start_up" : "Mumbai", "destination_up" : "Delhi" }, { "id" : "1", "route_name" : "6", "start_down" : "Delhi", "destination_down" : "Mumbai" }
How can I achieve this using a single query?
you can use an union
select id, route_name, start_up, destination_up
from my_table
where id ='1'
union
select id, route_name, start_down, destination_down
from my_table
where id ='1'