{
$cond: {
if: { $in: [`$$${field.fieldName}`, ['', null]] },
then: [],
else: `$$${field.fieldName}`,
},
},
In this condition, I also want to check the field.fieldName exits.
$exists: true,
then it will something like
if ( !filed.fieldName || field.fieldName === null || field.fieldName === '') then []
I am not finding any way to add $exits: true
or false
in this. Please help if can add something to this. Or any alternate way to achieve ?
You can use $or
Evaluates an expression and returns the value of the expression if the expression evaluates to a non-null value. If the expression evaluates to a null value, including instances of undefined values or missing fields, returns the value of the replacement expression.
{ $ifNull: [ <expression>, <replacement-expression-if-null> ] }
{
$cond: {
if: {
$or : [
{ $in: [`$$${field.fieldName}`, ['', null]] },
{ $ifNull: [`$$${field.fieldName}`, ""] }
]},
then: [],
else: `$$${field.fieldName}`,
}
},
Bear in mind, " field.fieldName exists " might be different to " field.fieldName is not null ".
Consider special values like this:
db.collection.insertMany([{ a: 1 }, { a: '' }, { a: undefined }, { a: null }, {}])
db.collection.aggregate([
{
$set: {
type: { $type: "$a" },
ifNull: { $ifNull: ["$a", null] },
defined: { $ne: ["$a", undefined] },
existing: { $ne: [{ $type: "$a" }, "missing"] }
}
}
])
{ a: 1, type: double, ifNull: 1, defined: true, existing: true }
{ a: "", type: string, ifNull: "", defined: true, existing: true }
{ a: undefined, type: undefined, ifNull: null, defined: false, existing: true }
{ a: null, type: null, ifNull: null, defined: true, existing: true }
{ type: missing, ifNull: null, defined: false, existing: false }
So, condition could be this one, depending on your requirements:
{
$cond: {
if: { $ne: [{ $type: "$field.fieldName" }, "missing"] },
then: [],
else: "$field.fieldName",
}
}
You just need to put $ifNull
in else part, if it's not exists it will return []
,
{
$cond: {
if: {
$in: [`$$${field.fieldName}`, ["", null]]
},
then: [],
else: { $ifNull: [`$$${field.fieldName}`, []] }
}
}
Input:
[
{ "key": null },
{ "key": "" },
{ "A": "a" }
]
Result:
[
{
"key": null,
"status": []
},
{
"key": "",
"status": []
},
{
"status": []
}
]
Second approach, if you want to add an existing condition in if
part you can try condition with $or
,
$type
will return the field's data type the missing field type is "missing" {
$cond: {
if: {
$or: [
{ $eq: [{ $type: `$$${field.fieldName}` }, "missing"] },
{ $in: [`$$${field.fieldName}`, ["", null]] }
]
},
then: [],
else: `$$${field.fieldName}`
}
}
Try this:
{
$cond: {
if: { $ne : [`$$${field.fieldName}`, undefined] },
then: [],
else: `$$${field.fieldName}`,
},
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.