Yes, MongoDB can easily index a null value. Let us first create a collection with documents −
> db.demo170.createIndex({"Value":1},{unique:true}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo170.insert({"Value":100}); WriteResult({ "nInserted" : 1 }) > db.demo170.insert({"Value":null}); WriteResult({ "nInserted" : 1 }) > db.demo170.insert({"Value":90}); WriteResult({ "nInserted" : 1 }) > db.demo170.insert({"Value":78}); WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo170.find();
This will produce the following output −
{ "_id" : ObjectId("5e369b789e4f06af551997da"), "Value" : 100 } { "_id" : ObjectId("5e369b7c9e4f06af551997db"), "Value" : null } { "_id" : ObjectId("5e369b809e4f06af551997dc"), "Value" : 90 } { "_id" : ObjectId("5e369b969e4f06af551997dd"), "Value" : 78 }
Following is the query to index null −
> db.demo170.find().sort({Value:1});
This will produce the following output −
{ "_id" : ObjectId("5e369b7c9e4f06af551997db"), "Value" : null } { "_id" : ObjectId("5e369b969e4f06af551997dd"), "Value" : 78 } { "_id" : ObjectId("5e369b809e4f06af551997dc"), "Value" : 90 } { "_id" : ObjectId("5e369b789e4f06af551997da"), "Value" : 100 }