How to validate documents before insert or update in MongoDB?


To validate documents, use the concept of validation. Following is the query −

> db.createCollection("demo356", {validator: {
... $and: [ {"FirstName": {$type: "string", $exists: true}} ]
... }})
{ "ok" : 1 }

Let us create a collection with documents −

> db.demo356.insertOne({"FirstName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e568d49f8647eb59e5620c7")
}
> db.demo356.insertOne({"FirstName":909});
2020-02-26T20:52:58.497+0530 E QUERY [js] WriteError: Document failed validation :
WriteError({
   "index" : 0,
   "code" : 121,
   "errmsg" : "Document failed validation",
   "op" : {
      "_id" : ObjectId("5e568d52f8647eb59e5620c8"),
      "FirstName" : 909
   }
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9
@(shell):1:1

Display all documents from a collection with the help of find() method −

> db.demo356.find();

This will produce the following output −

{ "_id" : ObjectId("5e568d49f8647eb59e5620c7"), "FirstName" : "Chris" }

Updated on: 02-Apr-2020

486 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements