How to use ORDERBY in MongoDB if there are possible null values?

MongoDBDatabaseBig Data Analytics

If there are null values also, then implement ORDERBY using sort().

Note − Since, starting in MongoDB v3.2, the $orderby operator deprecated in the mongo shell. Use cursor.sort() instead.

Let us create a collection with documents −

> db.demo530.insertOne({"Name":"Chris"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b2990ef4dcbee04fbbbec")
}
> db.demo530.insertOne({"Name":null});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b2991ef4dcbee04fbbbed")
}
> db.demo530.insertOne({"Name":"David"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b2992ef4dcbee04fbbbee")
}
> db.demo530.insertOne({"Name":"Adam"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b2995ef4dcbee04fbbbef")
}
> db.demo530.insertOne({"Name":null});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b2999ef4dcbee04fbbbf0")
}
> db.demo530.insertOne({"Name":"Carol"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b299eef4dcbee04fbbbf1")
}

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

> db.demo530.find();

This will produce the following output −

{ "_id" : ObjectId("5e8b2990ef4dcbee04fbbbec"), "Name" : "Chris" }
{ "_id" : ObjectId("5e8b2991ef4dcbee04fbbbed"), "Name" : null }
{ "_id" : ObjectId("5e8b2992ef4dcbee04fbbbee"), "Name" : "David" }
{ "_id" : ObjectId("5e8b2995ef4dcbee04fbbbef"), "Name" : "Adam" }
{ "_id" : ObjectId("5e8b2999ef4dcbee04fbbbf0"), "Name" : null }
{ "_id" : ObjectId("5e8b299eef4dcbee04fbbbf1"), "Name" : "Carol" }

Following is the query to implement ORDERBY in MongoDB if there are null values also using sort() −

> db.demo530.aggregate([
...    {$match: {"Name": {$exists: true}}}
...    ,
...    {$sort: { "Name": 1}}
... ]);

This will produce the following output −

{ "_id" : ObjectId("5e8b2991ef4dcbee04fbbbed"), "Name" : null }
{ "_id" : ObjectId("5e8b2999ef4dcbee04fbbbf0"), "Name" : null }
{ "_id" : ObjectId("5e8b2995ef4dcbee04fbbbef"), "Name" : "Adam" }
{ "_id" : ObjectId("5e8b299eef4dcbee04fbbbf1"), "Name" : "Carol" }
{ "_id" : ObjectId("5e8b2990ef4dcbee04fbbbec"), "Name" : "Chris" }
{ "_id" : ObjectId("5e8b2992ef4dcbee04fbbbee"), "Name" : "David" }
raja
Published on 13-May-2020 07:43:15
Advertisements