2

I'm facing a duplicate key error without finding a solution. I have a compound key created using the following command:

   db.test.createIndex({"a":1,"b":1,"date":1},{unique:true})

then I inserted a document:

   {
      "a": "test_a",
      "b": "test_b",
      "date": "20170710",
      "data": "testing"
   }

and until here everything is ok. Now when I try to insert the following document:

   {
      "a": "test_a",
      "b": "test_b",
      "date": "20170711",
      "data": "testing"
   }

I get E11000 duplicate key error collection. Why this is happening if the index is different in each document? Thanks

  • Does this return anything: `db.test.find({"a": "test_a", "b": "test_b", "date": "20170711"});` – Alex Jul 12 '17 at 13:17
  • Do you have any other unique indexes on your test collection? Can you include the actual duplicate key error message (which should have the details of the index and duplicate key)? If your set up is exactly as currently described the two documents have different keys. – Stennie Jul 12 '17 at 13:21
  • @Stennie I simplified the example, just to not post the real data that I'm using in my db, and yes I have other unique indexes in the collection. Here is the error reported when I'm trying to insert a new data with a new compound key: "errmsg" : "E11000 duplicate key error collection: statistics.impressions_distribution index: client_id_1_data_1_session_name_1 dup key: { : \"client_1\", : null, : \"client_1_20170710_20170716\" }" } – Karina Panucia Jul 12 '17 at 14:05
  • The duplicate key error message includes the index name and values for the conflicting key so you can use those to find the existing document. Missing fields in a compound index will be [indexed as `null`](https://docs.mongodb.com/manual/core/index-unique/#unique-index-and-missing-field), so it looks like you have an existing document missing the second field in the index (`data`) and are trying to insert a new document also missing that field. Is `data` in the index perhaps a typo for `date` or is this actually the intended field? – Stennie Jul 13 '17 at 03:11
  • 2
    @Stennie, I found the error, silly me, I was erroneously writing `date` instead of `data`. Thanks. – Karina Panucia Jul 13 '17 at 08:13

0 Answers0