由于索引

时间:2016-03-26 06:52:45

标签: mongodb mongoimport

我有一个包含以下字段的集合:

name
type
color

我还有一个唯一索引name_1_type_1

假设有一个数据集:

[{
  name: "name1",
  type: "type1",
  color: "blue"
}, {
  name: "name2",
  type: "type1",
  color: "green"
}]

使用mongoimport我创建初始数据集。

现在,我需要更新集合以实现以下3个目标:

  1. 在下面的代码段中插入新文档(例如name1 - type2
  2. 在现有文档中更新color(例如,blue中的red - > name1
  3. 在某些文档中添加新的可选字段shape

    [
        {
            name: "name1",
            type: "type1",
            color: "red",
            shape: "circle"
        }, 
        {
            name: "name1",
            type: "type2",
            color: "green",
            shape: "rectangle"
        }
    ]
    
  4. 但是,在上面的json文件上执行mongoimport --upsert时,我得到:

      

    插入文档时出错:E11000重复键错误集合:   test.col1索引:name_1_type_1 dup key

    也许我以错误的方式使用mongoimport

    如何使用mongoimport实现上述3个upsert目标?

1 个答案:

答案 0 :(得分:3)

您似乎错过了--upsertFields选项。没有它mongoimport假设你的意思是_id,特别是如果在导入的文件中不存在,那么它只是试图一直“插入”新项目。因此重复键错误。

因此,如果您指定基于唯一键的字段:

mongoimport -d database -c collection --upsert --upsertFields name,type input.json

然后你应该得到如下结果:

{
        "_id" : ObjectId("56f6332a49ec4ea8330063b6"),
        "name" : "name1",
        "type" : "type1",
        "color" : "red",
        "shape" : "circle"
}
{
        "_id" : ObjectId("56f6332a49ec4ea8330063b7"),
        "name" : "name2",
        "type" : "type1",
        "color" : "green"
}
{
        "_id" : ObjectId("56f633d4824b97f80d3714b1"),
        "name" : "name1",
        "type" : "type2",
        "color" : "green",
        "shape" : "rectangle"
}

请注意,在现代版本中,当您使用--upsertFields时隐含--upsert

N.B。如果您的数据采用这种方式构建,则可能还需要--jsonArray