如何只导入非现有文件?

Jol*_*oly 2 mongodb

我正在使用mongo import来导入一堆jsons,我正在寻找一种只导入不存在的记录的方法(可以通过oid检查).我尝试使用--upsert但它更新了记录,如果它已经存在,我想忽略它.

有任何想法吗...?

Mar*_*arc 10

mongoimport的默认行为不应该是覆盖现有文档:在JS shell中,我在集合"testimport"中创建了一个文档

> db.testimport.save({_id:1, x:"a"})
> db.testimport.find()
{ "_id" : 1, "x" : "a" }
> 
Run Code Online (Sandbox Code Playgroud)

以下是import.json文件的内容.它包含2个文档,一个具有唯一的_id,另一个具有重复的_id.

import.json
{_id:1, x:"b"}
{_id:2, x:"b"}
Run Code Online (Sandbox Code Playgroud)

在新的终端窗口中,运行mongoimport:

$ ./mongoimport -d test -c testimport import.json -vvvvv 
Wed Apr  4 19:03:48 creating new connection to:127.0.0.1
Wed Apr  4 19:03:48 BackgroundJob starting: ConnectBG
Wed Apr  4 19:03:48 connected connection!
connected to: 127.0.0.1
Wed Apr  4 19:03:48 ns: test.testimport
Wed Apr  4 19:03:48 filesize: 29
Wed Apr  4 19:03:48 got line:{_id:1, x:"b"}
Wed Apr  4 19:03:48 got line:{_id:2, x:"b"}
imported 2 objects
$
Run Code Online (Sandbox Code Playgroud)

即使mongoimport的输出表示导入了两个对象,但_id:1的文档仍未被覆盖.

> db.testimport.find()
{ "_id" : 1, "x" : "a" }
{ "_id" : 2, "x" : "b" }
>
Run Code Online (Sandbox Code Playgroud)

如果使用--upsert标志,则将更新_id:1的文档:

$ ./mongoimport -d test -c testimport import.json -vvvvv --upsert
Wed Apr  4 19:14:26 creating new connection to:127.0.0.1
Wed Apr  4 19:14:26 BackgroundJob starting: ConnectBG
Wed Apr  4 19:14:26 connected connection!
connected to: 127.0.0.1
Wed Apr  4 19:14:26 ns: test.testimport
Wed Apr  4 19:14:26 filesize: 29
Wed Apr  4 19:14:26 got line:{_id:1, x:"b"}
Wed Apr  4 19:14:26 got line:{_id:2, x:"b"}
imported 2 objects
$
Run Code Online (Sandbox Code Playgroud)

在JS shell中,我们可以看到_id:1的文档已经更新:

> db.testimport.find()
{ "_id" : 1, "x" : "b" }
{ "_id" : 2, "x" : "b" }
>
Run Code Online (Sandbox Code Playgroud)

这不是您遇到的行为吗?以上版本是使用2.1.1-pre版本测试的,但我不相信mongoimport代码已经改变了一段时间.