I am using C# MongoDB.Driver, Version=1.10.1.73.
Note I am aware of this question, not my issue whatsoever.
Error message:
MongoDB.Driver.MongoWriteConcernException: Command 'createIndexes' failed: exception: Index with name: filename_1_uploadDate_1 already exists with different options (response: { "createdCollectionAutomatically" : false, "numIndexesBefore" : 4, "errmsg" : "exception: Index with name: filename_1_uploadDate_1 already exists with different options", "code" : 85, "ok" : 0.0 })
MongoDatabase _database;
var query = MongoDB.Driver.Builders.Query.And(
MongoDB.Driver.Builders.Query.EQ(ColumnFilename, filePath),
MongoDB.Driver.Builders.Query.EQ(ColumnWidth, width),
MongoDB.Driver.Builders.Query.EQ(ColumnHeight, height));
var mongoFileInfo = _database.GridFS.FindOne(query);
if (mongoFileInfo != null) {
var mongoStream = mongoFileInfo.OpenRead();
if (/*some condition*/) {
mongoStream.Close();
mongoStream.Dispose();
mongoFileInfo.Delete(); // exception here
}
Full stack trace:
MongoDB.Driver.MongoCollection.CreateIndex(IMongoIndexKeys keys, IMongoIndexOptions options)
MongoDB.Driver.MongoCollection.CreateIndex(IMongoIndexKeys keys)
MongoDB.Driver.MongoCollection.CreateIndex(String[] keyNames)
MongoDB.Driver.GridFS.MongoGridFS.EnsureIndexes(Int32 maxFiles)
MongoDB.Driver.GridFS.MongoGridFS.EnsureIndexes()
MongoDB.Driver.GridFS.MongoGridFSFileInfo.Delete()
The filename_1_uploadDate_1
index is created by default on my Mongo server version 3.0.7. Default setting for unique is 'not unique'. Whenever some piece of code was forcing this index to be unique(as I think it should), aforementioned exception occurred on deleting from Mongo.
Resolution: if index not present create it, if present and unique then recreate as not unique.
CommandResult cr = null;
IndexOptionsDocument NotUnique = new IndexOptionsDocument("unique", false);
IndexKeysDocument fileNameUploadDateIdx = new IndexKeysDocument(
new List<BsonElement> {
new BsonElement(ColumnFilename, 1),
new BsonElement(ColumnUploadDate, 1) });
var index = indexes.FirstOrDefault(
i => i.Key.Equals(fileNameUploadDateIdx.ToBsonDocument()));
if (index == null)
{
cr = files.CreateIndex(fileNameUploadDateIdx, NotUnique);
if (!cr.Ok) {
//Cannot create uploadDate index
}
}
else if (index.IsUnique)
{
cr = files.DropIndexByName(index.Name);
if (!cr.Ok) {
// Cannot drop index filename_1_uploadDate_1.
}
else
{
cr = files.CreateIndex(fileNameUploadDateIdx, NotUnique);
if (!cr.Ok) {
//Cannot create uploadDate index
}
}
}
According to Mongo docs version 3.2 there's no way to modify options on an index without dropping and creating it all over again. This question tackles this too, and this answer provides an extension method for wrapping this drop and recreate from scratch behavior.