Can I require an attribute to be set in a mongodb collection? (not null)

For required fields use $AND in collection's validator with "$exists: true":

db.createCollection("foo", {
  validator: {
    $and: [ {"bar": {$type: "string", $exists: true}} ]
})

more info here https://www.compose.com/articles/document-validation-in-mongodb-by-example/


For anyone finding their way here, you can use 'required', such that:

db.createCollection("person", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "name" ],
         properties: {
            name: {
               bsonType: "string",
               description: "must be a string and is required"
            }
         }
      }
   }
}

You can read more in the documentation, here and here.

Note, that an alternative approach is to use Mongodb by means of mongoose, which allows specifying this directly at the field level:

const person = new mongoose.Schema({
    name {
        type: String,
        required: true
    }
});

In Mongoose, you can use a validator to check if a field has been set before you save it. As far as I know, there is no way of specifying on a Schema that a field is required, so it requires a little more boilerplate code.