I am extending the solution provided at this example where I am adding multiple conditions within the "in" of operator $map. All the conditions need to be true so I'm using $and operator to combine them. The new condition checks whether a particular field exists as a key in the document. I am using operator $exists to check this. The code snippet to check this condition is
{
"isTypePattern": {
$exists: false
}
}
where the name of the field (to check for existence) is: isTypePattern. This snippet works independently however when embedded under $map operator it throws a compile error:
The code looks like following and here is the playground link:
db.collection.find({
"$expr": {
"$anyElementTrue": {
"$map": {
"input": "$entities",
"in": {
$and: [
{
"$regexMatch": {
"input": "Room1",
"regex": "$$this.id",
"options": "i"
},
},
{
"isTypePattern": {
$exists: false
}
}
]
}
}
}
}
})
So if someone can suggest how to embed $exists within $map operator that would be great
CodePudding user response:
Maybe something like this:
db.collection.find({
"$expr": {
"$anyElementTrue": {
"$map": {
"input": "$entities",
"in": {
$and: [
{
"$regexMatch": {
"input": "Room1",
"regex": "$$this.id",
"options": "i"
},
},
{
$eq: [
{
$type: "$$this.isTypePattern"
},
"missing"
]
}
]
}
}
}
}
})
Explained:
$expr allow using $type and aggregation comparison operators like $eq,$ne,$lt,$gt that can be used for the case , but do not support $exists.