[SERVER-12573] Extend $ifNull to accept more than two arguments was Add $any/$first/$oneOf operator to projection Created: 02/Feb/14  Updated: 07/Dec/20  Resolved: 04/Dec/20

Status: Closed
Project: Core Server
Component/s: Aggregation Framework
Affects Version/s: None
Fix Version/s: 4.9.0

Type: Improvement Priority: Minor - P4
Reporter: Tyler Brock Assignee: Hana Pearlman
Resolution: Done Votes: 3
Labels: expression, neweng
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Depends
is depended on by CSHARP-3282 Extend $ifNull to accept more than tw... Closed
is depended on by JAVA-3900 Extend $ifNull to accept more than tw... Closed
Documented
is documented by DOCS-14034 Investigate changes in SERVER-12573: ... Closed
Backwards Compatibility: Fully Compatible
Sprint: Query 2020-11-30, Query 2020-12-14
Participants:

 Description   

This could be described as $ifNull expression that accepts multiple arguments (rather than current two only). First non-null expression would be used.

Original description:

It would be great if instead of making a long list of conditionals you could use any $any operator to get the first of the fields that exists.

Ex:

var docs = [
  { 'a': true },
  { 'b': true },
  { 'a': true}
  ...
]

{ '$project':
  { 'wow':
    { '$any': [ '$a', '$b', '$b.nested', ... ] }
  }
}

This would make it easy to project an _id for use by a $group stage in situations where you have varied document schema.

For example, the next stage of the pipeline could be:

{ $group: 
  { 
    _id: { wow: '$wow' },
    count: { '$sum': 1 }
  }
}



 Comments   
Comment by Githook User [ 04/Dec/20 ]

Author:

{'name': 'Hana Pearlman', 'email': 'hana.pearlman@mongodb.com'}

Message: SERVER-12573 Extend $ifNull to accept more than two arguments
Branch: master
https://github.com/mongodb/mongo/commit/8284eb2c2eedf795293b5ebc349e468e8666073c

Comment by Asya Kamsky [ 23/Jan/18 ]

This could also be implemented by allowing $ifNull to accept more than two arguments and returning the first one that's not Null-ish.

{ '$project':
  { 'wow':
    { '$ifNull': [ '$a', '$b', '$b.nested', ... ] }
  }
}

Comment by Asya Kamsky [ 25/Feb/16 ]

Now that I think about, this is just syntactic sugar for repeated $ifNull expressions - going off of "get the first of the fields that exists"...

Comment by Charlie Swanson [ 25/Jun/15 ]

If I'm understanding this correctly, this is exactly what $or does? Python's any function is equivalent to $or. Or is this meant to be equivalent to short-circuiting as a list of or expressions, returning the first true-ish value, not simply true if any are true?
e.g.

>>> 0 or 0.0 or False or "" or 3 or 4
3

Generated at Thu Feb 08 03:28:54 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.