4

I want to build a string from concatenating some fields, but I want to check the value of each field before I decide to concatenate it.

//syntax:
{$projection:{fieldName:{$concat:["$field1","-","$field2","$field3"]}}}

what I want?

fieldName=($field1!=null?"$field1-":"")+"$field2"+($field3=="ok"?"approved":"pending")

1 Answer 1

8

For the first case (null), you would use the $ifNull operator. This will return a default value if the field is null or missing.

For the second case, use the $cond operator.

fieldName:{
 $concat:
 [
  {$ifNull:["$field1", ""]},
  "-",
  "$field2", 
  {$cond:[{$eq:['$field3', 'ok']}, "approved", "pending"] }
 ]
}


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

Comments

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.