3
votes

I have the following code:

db.foo.insert([{_pos:1,b:12},{_pos:2,a:23},{_pos:3,c:12}])
db.foo.createIndex( { "_pos" : 1 }, { unique:  true } )
db.foo.update({}, { "$inc" : {"_pos" : 1} }, { multi : true })

The last line gives me the following error:

E11000 duplicate key error index: JsonTableTemp.foo.$_pos_1 dup key: { : 2.0 }

Adding $isolated to the query doesn't help.

How can I increment the _pos field without dropping the index first?

I use mongodb 3.2.6

1
I just tried this and the createIndex threw the error for me. The update actually worked perfectly when I removed the { unique: true } from the second line.dyouberg
@dyouberg: Why did createIndex fail? Which mongodb version are you using?Dreamcooled
Mongo Version 3.2.0 > db.foo.createIndex( { "_pos" : 1 }, { unique: true } ) { "ok" : 0, "errmsg" : "E11000 duplicate key error collection: test.foo index: _pos_1 dup key: { : 1.0 }", "code" : 11000 }dyouberg
How is that possible? Are you sure your collection is emtpy and does really only contain 3 documents?Dreamcooled
Hmm you're right, I think I copy pasted the first line twice. I had 6 entries. I just tried it again and got the same results you did. Let me take a better look.dyouberg

1 Answers

3
votes

Ok I got it...

Since you are making the indexes unique - the values cannot ever share the same value. The values are [1,2,3]. The increment is an atomic operation by MongoDB so they occur one at a time... First would be [2,2,3] then [2,3,3] then finally [2,3,4].

To prove this... simply reverse the values to [3,2,1] to begin.

> db.foo5.insert([{_pos:3,b:12},{_pos:2,a:23},{_pos:1,c:12}])
BulkWriteResult({
    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 3,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})
> db.foo5.createIndex( { "_pos" : 1 }, { unique:  true } )
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}
> db.foo5.find()
{ "_id" : ObjectId("57a9f76cb28f053d25a821a5"), "_pos" : 3, "b" : 12 }
{ "_id" : ObjectId("57a9f76cb28f053d25a821a6"), "_pos" : 2, "a" : 23 }
{ "_id" : ObjectId("57a9f76cb28f053d25a821a7"), "_pos" : 1, "c" : 12 }
> db.foo5.update({}, { "$inc" : {"_pos" : 1} }, { multi : true })
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
> db.foo5.find()
{ "_id" : ObjectId("57a9f76cb28f053d25a821a5"), "_pos" : 4, "b" : 12 }
{ "_id" : ObjectId("57a9f76cb28f053d25a821a6"), "_pos" : 3, "a" : 23 }
{ "_id" : ObjectId("57a9f76cb28f053d25a821a7"), "_pos" : 2, "c" : 12 }