简体   繁体   中英

How find consecutive results in mongoose

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.

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' }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM