添加数组元素(如果尚未包含)

时间:2018-02-06 21:37:59

标签: arrays node.js mongodb postgresql sequelize.js

如果数组中不存在,我试图将数组添加到数组中。但是以下内容会创建重复值:

build/www

PostgreSQL / sequelize中是否有与MongoDB $ addToSet等效的函数?

2 个答案:

答案 0 :(得分:1)

引用MongoDB Manual

  

$ addToSet运算符向数组添加一个值,除非该值已经存在,在这种情况下$ addToSet对该数组不执行任何操作。

此SQL命令执行您的要求:

UPDATE "user"
SET    topics = topics || topicId
WHERE  uuid = id
AND    NOT (topics @> ARRAY[topicId]);
在这种情况下,

@>数组包含运算符和||数组到元素的连接。 Details in the manual here.

相关:

对NULL值不起作用。在这种情况下,请考虑:array_position(topics, topicId) IS NULL。参见:

可以将它包装成一个简单的函数:

CREATE OR REPLACE FUNCTION f_array_append_uniq (anyarray, anyelement)
  RETURNS anyarray LANGUAGE sql IMMUTABLE AS
 'SELECT CASE WHEN array_position($1,$2) IS NULL THEN $1 || $2 ELSE $1 END;'

并像这样使用它:

...
SET    topics = f_array_append_uniq (topics, topicId)
...

但是函数本质上不如添加WHERE条件。如果列值实际更改,则顶部的查询仅写入新的行版本。参见:

答案 1 :(得分:0)

我遇到了同样的问题,这就是我解决的方法。

Traceback (most recent call last):
      File "E:\Pyton Excel Extractions\dashboard.py", line 68, in <module>
        ax.bar(X + 0.00, lol[0], color = 'b', width = 0.25)
      File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\__init__.py", line 1438, in inner
        return func(ax, *map(sanitize_sequence, args), **kwargs)
      File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\axes\_axes.py", line 2430, in bar
        x, height, width, y, linewidth = np.broadcast_arrays(
      File "<__array_function__ internals>", line 5, in broadcast_arrays
      File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\stride_tricks.py", line 258, in broadcast_arrays
        shape = _broadcast_shape(*args)
      File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\stride_tricks.py", line 189, in _broadcast_shape
        b = np.broadcast(*args[:32])
    ValueError: shape mismatch: objects cannot be broadcast to a single shape

尽管绝对感觉有更好的方法。