Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
A mongo operator I love to use is
$ifNull
, but sometimes this doesn't cover all the cases I need to cover, like for example an empty string. Is there an operator that works like the
$ifNull
operator (but with other conditions getting checked, like empty string), all in a single step? I just need to default the value if it's null or empty string. Below is a snippet of a query I'm doing currently:
//ex docs:
"_id": "1",
"field": {
"value": "test"
"_id": "2",
"field": {
"value": ""
"_id": "3"
"field": {
"value": null
//step in query where I'm checking ifNull:
$project: {
resValue: {
$ifNull: ["$field.value", "No Data"]
I'm trying to google around but see a lot of solutions involving $function, or just matching out the results with empty strings. This doesn't work in my case because I need all the documents included, but just need to default the resValue to "No Data" if it's empty or null. I'm also trying to limit the complexity and keep the query as efficient as possible, so I figure it's best not to include a $function step before the project.
Currently running version 4.4.13 on my db.
I need to return the value of the field itself if it exists and isn't an empty string, but if it's empty string or null, return "No Data" or some other default string as resValue on the resultant doc.
You are already on the right track of using $ifNull
. You just need one more $cond
to check for empty string case.
db.collection.aggregate([
"$addFields": {
"resValue": {
"$cond": {
"if": {
$eq: [
"$ifNull": [
"$field.value",
"then": "No Data",
"else": "$field.value"
Here is the Mongo playground for your reference.
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.