mongo _id 字段重复键错误 [英] mongo _id field duplicate key error

查看:19
本文介绍了mongo _id 字段重复键错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 _id 字段作为字符串类型 IP 的集合.

I have a collection with the _id field as a IP with type String.

我使用的是猫鼬,但这是控制台上的错误:

I'm using mongoose, but here's the error on the console:

$ db.servers.remove()

$ db.servers.remove()

$ db.servers.insert({_id":1.2.3.4"})

$ db.servers.insert({"_id":"1.2.3.4"})

$ db.servers.insert({"_id":"1.2.3.5"}) <-- 抛出重复键:{ : null }

$ db.servers.insert({"_id":"1.2.3.5"}) <-- Throws dup key: { : null }

推荐答案

可能是因为您有一个索引,需要其中一个字段的唯一值,如下所示:

Likely, it's because you have an index that requires a unique value for one of the fields as shown below:

> db.servers.remove()
> db.servers.ensureIndex({"name": 1}, { unique: 1})
> db.servers.insert({"_id": "1.2.3"})
> db.servers.insert({"_id": "1.2.4"})
E11000 duplicate key error index: test.servers.$name_1  dup key: { : null }

您可以在集合上使用 getIndexes() 查看索引:

You can see your indexes using getIndexes() on the collection:

> db.servers.getIndexes()
[
    {
        "v" : 1,
        "key" : {
                "_id" : 1
        },
        "ns" : "test.servers",
        "name" : "_id_"
    },
    {
        "v" : 1,
        "key" : {
                "name" : 1
        },
        "unique" : true,
        "ns" : "test.servers",
        "name" : "name_1"
    }
]

这篇关于mongo _id 字段重复键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆