繁体   English   中英

如何在MongoDB中数组元素的开头和结尾的字段中找到两个子字符串?

[英]How to find two substrings in a field at the beginning and the end of an array-element in MongoDB?

我在MongoDB中有一个集合,看起来像这样:

{
    "_id" : "ABCDEFGHIJK",
    "content" : {
        "arrayElements" : [ 
            "BD-cacf99afd87bd536da0162b2246f415e_FH",
            "BD-zhdfcf0bqa12qfT7jl10p9b3276o123p_HUCL",
            "WPG-bklcf10bqa12qg64jl99p9b3276o576a_HUCL",
            "EC-tzlscq10bqa12qg64jl19p9b3475o5z7_FH"
        ],
...
  }
}

另外,我有两个变量(SessionVariables)。 其中一个可以包含上述元素的第一部分(“-”之前的部分),另一个可以包含最后一部分(字符“ _”之后的部分)。 例如:

Session.set('firstPart', "BD");
Session.set('lastPart', "FH");

现在,我想使用findOne进行查询,该查询告诉我以上任何元素在第一部分中是否包含Session.get('firstPart') ,直到Session.get('lastPart')的字符"-" Session.get('lastPart')字符"_" 如果是这样,则请console.log('One element contains both parts')

我考虑过$regex ,但是不知道正确的语法。 我需要这样的东西:

if (collection.findOne({
      '_id': ABCDEFGHIJK), arrayElements: {
      $regex: /Session.get('firstPart')/ (AND) /
        Session.get('lastPart') / (IN ONE ELEMENT)
    }
  })) {
  console.log('One element contains both parts')
} else {
  console.log('None of the elements contains both parts')
}

在这种情况下,第一个变量包含“ BD”,第二个变量包含“ FH”,输出应为console.log('One element contains both parts')

尝试这个:

...{"arrayElements": {$regex:val}...

预先将字符串val声明为firstpart+"-.*_"+lastpart 您没有弄清楚两个变量中是否包含-和_,因此我认为它们没有。

暂无
暂无

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

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