imagine I have the next collection:
Files
_id | code |
---|---|
randomid | ZA/1/1/1-1#1 |
randomid | ZA/1/1/1-1#2 |
randomid | ZA/1/1/1-1#3 |
randomid | ZA/1/1/1-1#10 |
randomid | ZA/1/1/1-1#12 |
randomid | ZA/1/1/1-1#12-1 |
randomid | ZA/1/1/1-1#12-2-1 |
randomid | ZA/1/1/1-1#12-2-2 |
randomid | ZA/1/1/1-1#120 |
And I'm trying to get the "Childs" using:
Model.find({ code: { $regex: 'ZA/1/1/1-1#12'} })
And what I want:
[
{
"_id": "randomid",
"code": "ZA/1/1/1-1#12"
"__v": 0
},
{
"_id": "randomid",
"code": "ZA/1/1/1-1#12-1"
"__v": 0
},
{
"_id": "randomid",
"code": "ZA/1/1/1-1#12-2-1"
"__v": 0
},
{
"_id": "randomid",
"code": "ZA/1/1/1-1#12-2-2"
"__v": 0
},
]
But Im getting (same but including the #120):
[
{
"_id": "randomid",
"code": "ZA/1/1/1-1#12"
"__v": 0
},
{
"_id": "randomid",
"code": "ZA/1/1/1-1#12-1"
"__v": 0
},
{
"_id": "randomid",
"code": "ZA/1/1/1-1#12-2-1"
"__v": 0
},
{
"_id": "randomid",
"code": "ZA/1/1/1-1#12-2-2"
"__v": 0
},
{
"_id": "randomid",
"code": "ZA/1/1/1-1#12-2-2"
"__v": 0
},
{
"_id": "randomid",
"code": "ZA/1/1/1-1#120"
"__v": 0
},
]
So, that's why I'm looking for help, how do I prevent this from happening? Thanks.
CodePudding user response:
If I understood your question correctly:
You want to get the children/consecutive items which might be defined with this code format:
ZA/1/1/1-1#12
ZA/1/1/1-1#12-SOMETHING
Which translates to ZA/1/1/1-1#12(\-. )?$
, or /ZA\/1\/1\/1\-1#12(\-. )?$/
.
These results match what you wanted
test> db.sth.find().pretty()
[
{ _id: 'randomid', code: 'ZA/1/1/1-1#12' },
{ _id: 'randomid', code: 'ZA/1/1/1-1#12-1' },
{ _id: 'randomid', code: 'ZA/1/1/1-1#12-2-2' },
{ _id: 'randomid', code: 'ZA/1/1/1-1#120' }
]
test> db.sth.find({ code: { $regex: "ZA/1/1/1-1#12(\-. )?$"} }).pretty()
[
{ _id: 'randomid', code: 'ZA/1/1/1-1#12' },
{ _id: 'randomid', code: 'ZA/1/1/1-1#12-1' },
{ _id: 'randomid', code: 'ZA/1/1/1-1#12-2-2' }
]
test> db.sth.find({ code: { $regex: /ZA\/1\/1\/1\-1#12(\-. )?$/} }).pretty()
[
{ _id: 'randomid', code: 'ZA/1/1/1-1#12' },
{ _id: 'randomid', code: 'ZA/1/1/1-1#12-1' },
{ _id: 'randomid', code: 'ZA/1/1/1-1#12-2-2' }
]