M
M
Makcimka2021-01-01 11:31:06
PostgreSQL
Makcimka, 2021-01-01 11:31:06

How to insert into a Postgresql table from an array of objects?

Given an array with a large number of objects:

const arryTest = [
{
name: 'name1',
commens: 'commens1',
like: 2,
date: '01,01,2022'
},
{
name: 'name2',
commens: 'commens2',
like: 25,
date: '01,01,2022'
},
{
name: 'name3',
commens: 'commens3',
like: 35,
date: '01,01,2022'
},
]

In Mongodb, I would insert this easily with db.collection.insertMany(arryTest).
And in the case of PostgreSQL, will you have to use a cycle?
The table has id, name, comments, date columns.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2021-01-01
@rozhnev

Function: json_array_elements

create table comments (
        "name" varchar,
  	"commens" varchar,
  	"like" int,
  	"date" timestamp
);

insert into comments
select (json_populate_record(null::comments, value)).* from json_array_elements('[
{
    "name": "name1",
    "commens": "commens1",
    "like": 2,
    "date": "2022-01-01"
},{
    "name": "name2",
    "commens": "commens2",
    "like": 2,
    "date": "2022-01-01"
},{
    "name": "name3",
    "commens": "commens3",
    "like": 2,
    "date": "2022-01-01"
}
]');

select * from comments;

PostgreSQL fiddle

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question