E11000 duplicate key error collection

I have an index in collection “persons” which shall avoid inserting duplicate documents with the same person name. This has worked the last month. Now the aggregation from another collection stops inserting documents with names that are not duplicates.

This must be incorrect? Or has there been a change to functionality?

Hello @Christina_Sandberg, welcome to the MongoDB Community forum.

I have an index in collection “persons” which shall avoid inserting duplicate documents with the same person name.

That is the Unique Index on the person’s “name” field. This will not allow an operation to insert a new document with an existing name or update a document with an updated existing name. If such an operation is tried it fails with an "E11000 duplicate key error collection: database.collection index_name … ".

As long as the name is unique within the collection, the name is inserted (or updated).

I suggest that you share the data and code (the scenario in detail) which you think is causing the problem.

1 Like

As you can see, there is 1 record in collection “persons” and the aggregation pipeline from the collection “transactions” looks like this:

[
{
‘$project’: {
‘person_name’: 1
}
}, {
‘$out’: ‘persons’
}
]

1 Like

So what is happening when you run the above Aggregation query?

The ‘persons’ collection still only has 1 document.

Sometimes a temporary collection is added by MongoDB - but not this time.

When you use the $out stage, it totally replaces the existing collection. The error E11000 duplicate key error ... { person_name: 'Carl-Fredrik Linder' } is saying that the aggregation query is trying to create a document with person_name: 'Carl-Fredrik Linder' more than once - that is violating the unique index constraint on the person_name in the persons collection.

1 Like

You can ignore the temporary collection showing in the messages - it is part of the process that creates the collection in the $out stage - it is “normal”.

i was getting this error, thanks for the solution!