Reputation: 8878
I'm using MongoDB and i have the following records:
{
name: "a",
status: [
{ age: 15, closed: true},
{ age: 38, closed: true},
{ age: 42, closed: false},
]
},
{
name: "b",
status: [
{ age: 29, closed: true},
{ age: 5, closed: false},
]
}
I want to check if the before last object in status has for example age = 29.
so for that i have this working query:
db.col.find({
$expr: {
$eq: [
29,
{
$let: {
vars: { beforeLast: { $arrayElemAt: [ "$status", -2 ] } },
in: "$$beforeLast.age"
}
}
]
}
})
but i want now to check for example if age contain a value like "2". i need to use regex expression. is there anyway to convert that query to use regex inside/instead $eq
operator ?
PS: i don't want to use aggregation because i'm working with an old version.
Upvotes: 1
Views: 234
Reputation: 1134
Try with aggregation
db.collection.aggregate([
{
$project:
{
last: { $arrayElemAt: [ "$status", -2 ] },
}
},
{$addFields:{
ageInString: { $substr: [ "$last.age", 0, 3 ] }
}},
{$match:{ageInString:{ $regex: '^2' }}}
])
Upvotes: 0
Reputation: 46481
You can use $indexOfCP
to find sub string inside an string character
db.collection.find({
"$expr": {
"$ne": [
{
"$indexOfCP": [
{ "$toLower": {
"$let": {
"vars": {
"beforeLast": {
"$arrayElemAt": [
"$status",
-2
]
}
},
"in": "$$beforeLast.age"
}
}},
"2"
]
},
-1
]
}
})
Upvotes: 1