Insert duplicate documents into MongoDB

32 views
Skip to first unread message

Praneeth Tvss.

unread,
Mar 16, 2018, 6:53:00 AM3/16/18
to mongodb-user
Hi EveryOne,

I have a record present in MongoDB with the following format:
```
{
    _id : 1,
    name: Praneeth,
    age: 22
}
```
- Now I want to add one more record from the file. In that file, we are having same "_id" for the record. We want to load this file using `mongoimport`.
```
{
    _id: 1,
    name: Tvss,
    age: 22
}
```
- When we try to load the new data, we are getting duplicate key Error, because {_id: 1} already exists.
- How can we load the data to Mongo with same "_id"(duplicating)?

Can anyone please help me with this issue ?.
If anyone couldn't able to understand the issue, please let me know...

Thanks,
Praneeth.

Stephen Steneker

unread,
Mar 17, 2018, 2:31:54 AM3/17/18
to mongodb-user
On Friday, 16 March 2018 21:53:00 UTC+11, Praneeth Tvss. wrote:
- When we try to load the new data, we are getting duplicate key Error, because {_id: 1} already exists.

Hi Praneeth,

This is an expected error: the _id field is the primary key for a document and must be unique.

- How can we load the data to Mongo with same "_id"(duplicating)?

Since duplicate values are not allowed in the _id field, you should either make your values unique or rename the field in your data file before importing. For example, you could rename your field to source_id and allow MongoDB to generate a unique ObjectID for the required _id field.

Regards,
Stennie

Praneeth Tvss.

unread,
Mar 17, 2018, 6:19:43 AM3/17/18
to mongodb-user
Hi Stennie,

Thank you very much.
It helps me.

Thanks,
Praneeth.
Reply all
Reply to author
Forward
0 new messages