node foreach循环插入数据库时如何跳过数据库中已有的重复数据(去重)
 发布于 11 年前  作者 heixiaoshan  8602 次预览  最后一次回复是 11 年前  来自 问答 

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

10 回复
ddzjs

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

ravenwang

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

leapon

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]
RanHuang

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

alsotang

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

  1. 如果想覆盖的话,参照 4L 的做法。 @RanHuang
  2. 如果不想覆盖的话,保存之前用唯一字段去 $in 查询一次,然后排除现有数据中哪些重复的,再存储。
heixiaoshan

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