When are mongodb indexes updated?

Question

Are mongodb indexes updated before the success of the write operation is reported to the application or index updates are running in the background? If they run in the background: is there a way to wait for the index update to complete?

Background

I have a document

person1obj = {
  email: 'user@domain.tld',
  [...]
}

in a collection peoplewhere a emailunique index is applied to the field . Now I would like to add another document

person2obj = {
  email: 'user@domain.tld',
  [...]
}

Obviously, I need to change the field email person1before I person2can insert. With mongoose, the code looks like

mongoose.model('Person').create(person1obj, function (err, person1) {
  // person1 has been saved to the db and 'user@domain.tld' is 
  // added to the *unique* email field index

  // change email for person1 and save
  person1.email = 'otheruser@domain.tld';
  person1.save(function(err, person1) {
    // person1 has been updated in the db

    // QUESTION: is it guaranteed that 'user@domain.tld' has been removed from
    //           the index? 

    // inserting person2 could fail if the index has not yet been updated
    mongoose.model('Person').create(person2obj, function (err, person2) {
      // ...
    });
  });
});

I saw a random failure of my unit tests with an error E11000 duplicate key error index, which made me wonder if index updates were running in the background.

, , mongodb , .

+4
2

FAQ ( ):

?

, , . , , MongoDB , , .

, , .

+3

, . , , , .

, , . , .

( Mongo - , , ), , , . , .

0

Source: https://habr.com/ru/post/1617481/


All Articles