It's a bit tricky, but you can achieve your case with this aggregation:
db.collection_name.aggregate([
{
"$addFields": {
"results": {
"$regexFindAll": {
"input": "$value",
"regex": "[0-9]+"
}
}
}
},
{
"$project": {
"number": {
"$convert": {
"input": {
"$reduce": {
"input": "$results",
"initialValue": "",
"in": {
"$concat": ["$$value", "$$this.match"]
}
}
},
"to": "int",
"onError": "no digit matched"
}
}
}
},
{
"$match": {
"number": 142
}
}
])
data:
> db.collection_name.find()
{ "_id" : ObjectId("5dfbf14671f3d8949c44881c"), "value" : "1rt 42" }
{ "_id" : ObjectId("5dfbf14671f3d8949c44881d"), "value" : "1 4sd 2" }
{ "_id" : ObjectId("5dfbf14671f3d8949c44881e"), "value" : "14 e 6" }
{ "_id" : ObjectId("5dfbf47c71f3d8949c44881f"), "value" : "test" }
after stage one $addFileds
will have something like this:
{
"_id" : ObjectId("5dfbf14671f3d8949c44881c"),
"value" : "1rt 42",
"results" : [
{
"match" : "1",
"idx" : 0,
"captures" : [ ]
},
{
"match" : "42",
"idx" : 4,
"captures" : [ ]
}
]
}
.
.
{
"_id" : ObjectId("5dfbf47c71f3d8949c44881f"),
"value" : "test",
"results" : [ ]
}
then after stage two $project
:
{ "_id" : ObjectId("5dfbf14671f3d8949c44881c"), "number" : 142 }
{ "_id" : ObjectId("5dfbf14671f3d8949c44881d"), "number" : 142 }
{ "_id" : ObjectId("5dfbf14671f3d8949c44881e"), "number" : 146 }
{ "_id" : ObjectId("5dfbf47c71f3d8949c44881f"), "number" : "no digit matched" }
and finally with the $match
you'll get your expected result:
{ "_id" : ObjectId("5dfbf14671f3d8949c44881c"), "number" : 142 }
{ "_id" : ObjectId("5dfbf14671f3d8949c44881d"), "number" : 142 }