简体   繁体   中英

MongoDB: Ensure that only one document can have a field set to true

I have a mongo collection with multiple configurations. However, at any one time, only one of these can be "active". I do this by setting an active tag to true.

CylonConfigurations = new Mongo.Collection('cylon_configurations');

Meteor.startup(function () {
  if (Meteor.isServer) {
    CylonConfigurations.upsert({
      host: '192.168.1.4',
      port: 23
    }, {
      $setOnInsert: {
        host: '192.168.1.4',
        port: 23,
        active: true
      }
    }, function (err, s) {
      if (!err) {
        const conn = CylonConfigurations.findOne({ active: true });
        Cylon.connect(conn.port, conn.host);
      }
    });
  }
});

However, the problem I am facing is the case that multiple items within this collection can have the boolean of active set to true , theoretically.

In MongoDB, is there any way to prevent this? Is there any way to ensure that only one document in a collection has a flag set to true, and all the others have it set to false?

You can add an unique sparse index on your active flag after removing flag values that are false. This will ensure only one document can have the active flag set to true (or false).

db.CylonConfigurations.createIndex( { "active": 1 }, { sparse: true,unique: true } )

Alternatively you could create a new collection that just stores the ObjectId of the currently active configuration, for example in a field called ActiveConfigurationId . In this model, you can just update this field to change the active configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM