2

I have the following MongoDB aggregate operation which is working fine but it also seems to be returning NULL values.

How can I ignore NULL values against projectIP field?

db.inventory.aggregate(
    [
     { $match:   {projectIP: { $exists:true }}},
     { $project: {projectIP: "$projectIP",_id : 0}},
     { $group:   {_id: "$projectIP"}},
     { $sort:    {projectIP: 1}}
    ];
)
6
  • { $match: { projectIP: { $exists:true }}} Commented May 14, 2019 at 13:29
  • @Anthony Winzlet unfortunately didn't seem to work. Added this after the $sort{} Commented May 14, 2019 at 13:39
  • Not after the $sort. This should be the top of the pipeline above $project Commented May 14, 2019 at 13:40
  • @Anthony Winzlet Added to the top as shown in updated question and sorry, still showing my NULL value in my select drop-down list. Commented May 14, 2019 at 13:43
  • 1
    Seems some of the keys contain null values. Add this as well { $match: { projectIP: { $exists:true, $ne: null }}} by replacing the first stage in your query Commented May 14, 2019 at 16:12

2 Answers 2

1

Seems some of the keys contain null values. Add this as well

{ $match: { projectIP: { $exists:true, $ne: null }}}

by replacing the first stage in your query

Sign up to request clarification or add additional context in comments.

Comments

1

You can assign a value (0 or anything) to them instead of a null value.

Here how you do it

projectIP: { $ifNull: [ "$projectIP", 0.0 ] }

3 Comments

Will this actually ignore the NULL value as I am displaying the values in a select drop-down list where I don't want to show any NULLs.
It will not ignore null values but will assign null fields a value. Useful if your code throws an exception with null values.
Thanks for the info but in this scenario, I need the null values ignored altogether.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.