I have this data in MongoDB.
{ _id: "abc*hello*today*123", "value": 123 },
{ _id: "abc*hello*today*999", "value": 999 },
{ _id: "xyz*hello*tomorrow*123", "value": 123 }
What I want is to group by the first part before "*{number}". This is what I want to achieve:
{
_id: "abc*hello*today",
results: [
{ _id: "abc*hello*today*123", "value": 123 },
{ _id: "abc*hello*today*999", "value": 999 }
]
},
{
_id: "xyz*hello*tomorrow",
results: [
{ _id: "xyz*hello*tomorrow*123", "value": 123 }
]
}
I tried this:
{
$group:{
"_id":"$_id".slice(0, -4)
}
}
2
Answers
You can work with regex as below:
The above regex will match and retrieve the value before the * and numbers.
Demo @ Regex 101
$set
– SetfirstPart
field.1.1.
$getField
– Get thematch
value from the object 1.1.1.1.1.1.
$regexFind
– Match the_id
with regex.$group
– Group byfirstPart
.$unset
– Remove theresults.firstPart
field.Demo @ Mongo Playground
Alternative solution: If your
_id
has always the same format(field1*field2*field3*numbers)
, you can use$split
+$slice
+$reduce
operatorsExplanation:
MongoPlayground