MongoDb background indexing and unique index

后端 未结 3 1915
南方客
南方客 2020-12-21 07:42

When you create an index in MongoDb. There are 2 options:

  • Do foreground indexing and lock all write operations while doing so
  • Do background indexing a
3条回答
  •  攒了一身酷
    2020-12-21 08:10

    @mltsy

    If, from another client, you're doing something like adding a duplicate document while the index is being built, it will insert the document without an error.

    I am not sure this is correct,as Mongodb Doc described as below:

    When building an index on a collection, the database that holds the collection is unavailable for read or write operations until the index build completes.

    I used the mongoose to test this :

    var uniqueUsernameSchema = new Schema({
        username: {
            index: { unique: true, background: false },
            type: String,
            required: true
        }
    })
    var U = mongoose.model('U1', uniqueUsernameSchema)
    var dup = [{ username: 'Val' }, { username: 'Val' }]
    U.create(dup, function (e, d) {
        console.log(e, d)
    })
    

    The unique index failed to build. This result showed the foreground option didnot block the write operation in MongoDB.

提交回复
热议问题