简体   繁体   English

如何在 mongoose 中找到连续的结果

[英]How find consecutive results in mongoose

imagine I have the next collection:想象我有下一个系列:

Files文件

_id _ID code代码
randomid随机数 ZA/1/1/1-1#1 ZA/1/1/1-1#1
randomid随机数 ZA/1/1/1-1#2 ZA/1/1/1-1#2
randomid随机数 ZA/1/1/1-1#3 ZA/1/1/1-1#3
randomid随机数 ZA/1/1/1-1#10 ZA/1/1/1-1#10
randomid随机数 ZA/1/1/1-1#12 ZA/1/1/1-1#12
randomid随机数 ZA/1/1/1-1#12-1 ZA/1/1/1-1#12-1
randomid随机数 ZA/1/1/1-1#12-2-1 ZA/1/1/1-1#12-2-1
randomid随机数 ZA/1/1/1-1#12-2-2 ZA/1/1/1-1#12-2-2
randomid随机数 ZA/1/1/1-1#120 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):但是我得到了(相同但包括#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(\-.+)?$/ .转换为ZA/1/1/1-1#12(\-.+)?$/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' }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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