I have JSON array in text type field in DB, and I want to check whether there are some elements in the array, and in that case, add some elements to this array and save it back to DB. The main issue I am having is that this text field looks like this:
["elem1","elem2","elem3"]
and I cannot figure out how to work with those double-quotes.
When I tried to_json it resulted in:
"[\"elem1\",\"elem2\",\"elem3\"]"
When I tried string_to_array:
{"[\"elem1\"","\"elem2\"","\"elem3\"]"}
I just need something like that:
['elem1', 'elem2', 'elem3']
To get a JSON array, simply cast it into json directly:
demo:db<>fiddle
SELECT '["elem1","elem2","elem3"]'::json
If you need a simple array (without JSON), you need to expand the elements of the JSON array (json_array_elements_text()) and aggregate them afterwards (array_agg()):
SELECT
array_agg(elems)
FROM mytable,
json_array_elements_text(mydata::json) AS elems
Related
I keep having a problem when filtering some data in postgresql.
For example, I want to filter by a json.
My jsons are saved in the following way
"[{\"Brand\":\"Leebo\"},{\"Housing Color\":\"Black\"},{\"Beam Type\":\"High Beam, Low Beam\"}]"
And let's say that I want to filter after
[{\"Brand\":\"Leebo\"}]
Shouldn't I write something like that in the query?
SELECT * FROM public.products
WHERE attributes is not NULL
AND attributes::text LIKE '%{\"Brand\":\"Leebo\"}%';
I tried also
SELECT * FROM public.products WHERE attributes::jsonb #> '"[{\"Material\":\"Artificial Leather\"}]"'
Because I won't receive data
Do you know how I could proceed differently?
But it only works if the column has all the data (eg if I give the exact data that is in the column)
Also, how could I search with whereIn?
You have an array in your JSONB because those characters ([ and ]) are array characters. If you are sure that you will always have only one array in your JSONB so you can use this:
SELECT * FROM public.products
WHERE attributes is not NULL
AND attributes[0]->>'Brand' = 'Leebo'
But if you can have several arrays inside JSONB then use jsonb_array_elements for extracting array elements, after then you can use JSONB operations like as ->>
i have created an array of strings "challengeMember" in Firestore database and i want to add data to it when user clicks a button, my database:
in my code am trying to update the array, every time user join a challenge, the challenge name will be added to this array i know how to access the array using:
FirebaseFirestore.instance.collection("Users").doc(user!.uid).update({'challengeMember': widget._challengeName});
but the problem with this it is not specifying the array index and it is not checking whether the index is empty or not, so how can i dynamically access this array and keep adding values.
Firestore has a special trick to add an array, and it goes like this:
await FirebaseFirestore.instance.collection('users').doc(uid).update({
'tokens': FieldValue.arrayUnion([token]),
});
See the FieldValue documentation on how to manipulate arrays.
I've a problem with a query condition. I would like to query a string inside an array that's also inside a map. I manage to receive the information complet without the where condition but when I do this condition I've an error.
My function to retrieve all information
My array with a map inside
If category is the only value inside the produits array items, you can check for its existence with array-contains:
collectionRef.where('produits', arrayContains({ 'categorie': 'Alimentation' }))
If there are more properties for the array item, you will need to specify all of them in the call to arrayContains. There is no way to query for a subset of the array item.
In such cases, a common workaround is to add a extra array field to the document with just the property values you want to query for. For example:
produitsCategories: ['Alimentation', '...']
With that field in place you can then query it with:
collectionRef.where('produitsCategories', arrayContains('Alimentation'))
I tried using an array of integers, then an array of strings. However, I keep getting the same error:
ERROR: operator does not exist: jsonb ?| integer[]
My query looks like this:
Bet.query()
.select(
'id',
'status'
)
.whereJsonSupersetOf('participants_ids', [userId])
.range()
.limit(10)
.orderBy('id', 'DESC')
.throwIfNotFound();
This is how the arrays are stored:
Each user has a screen where they can see their own bets against another users. In order to list bets for a logged in user, I need to check the participants_ids column. This is an array that contains the ids for the 2 users betting against each other.
The purpose of my query is to return a list of bets where the current user's Id is contained inside each bet's participants_ids array.
Originally, I tried user .where() and .orWhere() to check if the current user's id was either the bet host's id, or the bet challenger's id. This didn't give me the result I wanted though. So I decided an array column would be much better.
I can't seem to get this to work though. I've looked at a few posts, but they seem to be arrays of objects rather than arrays of ints or strings. I simply want to check the participants_ids array column contains the userId I am passing into the query.
I am also using Knex JS.
Any idea what I could be doing wrong here?
Thanks in advance.
.whereJsonXXX methods works only for postgresql jsonb columns.
For querying arrays column types you need to use array operators https://www.postgresql.org/docs/12/functions-array.html
Bet.query()
.select(
'id',
'status'
)
.where('participants_ids', '#>', [userId])
.range()
.limit(10)
.orderBy('id', 'DESC')
.throwIfNotFound();
Or maybe .where('participants_ids', '#>', val([userId]).asArray().castTo('integer[]')) if the array is not passed properly in the first example.
I want to select a single column in mgo which is array of strings currently using this returns a empty array
classifiedColl.Find(nil).Distinct("Tags", &tags)
and i want to group it how do i do it. The value i want to group is array of strings.