CNode

node foreach循环插入数据库时如何跳过数据库中已有的重复数据(去重)

问答
Hheixiaoshan发布于12 年前最后回复12 年前10 回复8808 浏览0 收藏

在循环过程中如何跳过数据库中已有的重复数据? 如何剔除本次循环中的重复数据?

查看回复

回复 (10)

D
ddzjs#1·12 年前

如果是sqlite数据库,那么可以用数据库内置的check特性,来阻止重复数据写入. 不知其他的数据库有这个特性没有. 不知道你是什么操作

R
ravenwang#3·12 年前

定义什么是重复数据先 mongo的话可以定义unique index,然后插入时吃掉所有duplicate key error

L
leapon#4·12 年前

underscore 里有 uniq 函数可以选出不重复的数组内容

uniq_.uniq(array, [isSorted], [iteratee]) Alias: unique 
Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iteratee function.

_.uniq([1, 2, 1, 3, 1, 4]);
=> [1, 2, 3, 4]
R
RanHuang#5·12 年前

针对网mongodb中插入重复数据,我所使用的笨方法是使用update函数代替insert,设置upsert属性为true,这样遇到不存在的数据则插入,遇到已经存在的数据则更新。

A
alsotang#6·12 年前

就看你想不想覆盖库中的重复数据了。

  1. 如果想覆盖的话,参照 4L 的做法。 @RanHuang
  2. 如果不想覆盖的话,保存之前用唯一字段去 $in 查询一次,然后排除现有数据中哪些重复的,再存储。
H
heixiaoshan#10·12 年前
引用 ravenwang定义什么是重复数据先 mongo的话可以定义unique index,然后插入时吃掉所有duplicate key error

@ravenwang 其实用unique index 试过了。但是插入的时候没有用duplicate

参与回复
登录后即可参与回复。登录