Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omit empty fields from MongoDB query result

Tags:

mongodb

Is there a way to omit empty fields (eg empty string, or an empty array) from MongoDB query results' documents (find or aggregate).

Document in DB:

{
    "_id" : ObjectId("5dc3fcb388c1c7c5620ed496"),
    "name": "Bill",
    "emptyString" : "",
    "emptyArray" : []
}

Output:

{
    "_id" : ObjectId("5dc3fcb388c1c7c5620ed496"),
    "name": "Bill"
}

Similar question for Elasticsearch: Omit null fields from elasticsearch results

like image 204
Sagar Gupta Avatar asked Oct 26 '25 19:10

Sagar Gupta


1 Answers

Please use aggregate function. If you want to remove key. you use $cond by using $project.

db.Speed.aggregate( [
   {
      $project: {
         name: 1,
         "_id": 1,
         "emptyString": {
            $cond: {
               if: { $eq: [ "", "$emptyString" ] },
               then: "$$REMOVE",
               else: "$emptyString"
            }
         },
         "emptyArray": {
            $cond: {
               if: { $eq: [ [], "$emptyArray" ] },
               then: "$$REMOVE",
               else: "$emptyArray"
            }
         }
      }
   }
] )
like image 65
Mahesh Bhatnagar Avatar answered Oct 29 '25 02:10

Mahesh Bhatnagar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!