Find a strict document that contains only a specific field with a fixed length?


You can use $where operator for this. Let us first create a collection with documents −

>db.veryStrictDocumentDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda4bcdb50a6c6dd317adb8")
}
> db.veryStrictDocumentDemo.insertOne({"StudentFirstName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda4bdbb50a6c6dd317adb9")
}
>db.veryStrictDocumentDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda4becb50a6c6dd317adba")
}
> db.veryStrictDocumentDemo.insertOne({"StudentFirstName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda4bfbb50a6c6dd317adbb")
}
> db.veryStrictDocumentDemo.insertOne({"StudentFirstName":"Bob","StudentLastName":"Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda4c6db50a6c6dd317adbc")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.veryStrictDocumentDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5cda4bcdb50a6c6dd317adb8"), "StudentFirstName" : "John", "StudentLastName" : "Doe", "StudentAge" : 23 }
{ "_id" : ObjectId("5cda4bdbb50a6c6dd317adb9"), "StudentFirstName" : "Larry" }
{ "_id" : ObjectId("5cda4becb50a6c6dd317adba"), "StudentFirstName" : "David", "StudentLastName" : "Miller" }
{ "_id" : ObjectId("5cda4bfbb50a6c6dd317adbb"), "StudentFirstName" : "Chris" }
{ "_id" : ObjectId("5cda4c6db50a6c6dd317adbc"), "StudentFirstName" : "Bob", "StudentLastName" : "Brown" }

Following is the query to get a specific field with fixed length −

> db.veryStrictDocumentDemo.find({
   "StudentFirstName": { $exists: true },
   "StudentLastName": { $exists: true },
   $where: function() { return Object.keys(this).length === 4 }
});

This will produce the following output −

{ "_id" : ObjectId("5cda4bcdb50a6c6dd317adb8"), "StudentFirstName" : "John", "StudentLastName" : "Doe", "StudentAge" : 23 }

Updated on: 30-Jul-2019

36 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements