[英]How to find two substrings in a field at the beginning and the end of an array-element in MongoDB?
I have a collection in MongoDB which looks like this: 我在MongoDB中有一个集合,看起来像这样:
{
"_id" : "ABCDEFGHIJK",
"content" : {
"arrayElements" : [
"BD-cacf99afd87bd536da0162b2246f415e_FH",
"BD-zhdfcf0bqa12qfT7jl10p9b3276o123p_HUCL",
"WPG-bklcf10bqa12qg64jl99p9b3276o576a_HUCL",
"EC-tzlscq10bqa12qg64jl19p9b3475o5z7_FH"
],
...
}
}
Additionally, I have two variables (SessionVariables). 另外,我有两个变量(SessionVariables)。 One of them could contain the first part of the above elements (the part before "-") and the other one could hold the last part (part after the character "_").
其中一个可以包含上述元素的第一部分(“-”之前的部分),另一个可以包含最后一部分(字符“ _”之后的部分)。 For example:
例如:
Session.set('firstPart', "BD");
Session.set('lastPart', "FH");
Now, I would like to perform a query with findOne, which tells me whether any of the above elements contains Session.get('firstPart')
at the first part until the character "-"
AND Session.get('lastPart')
after the character "_"
. 现在,我想使用findOne进行查询,该查询告诉我以上任何元素在第一部分中是否包含
Session.get('firstPart')
,直到Session.get('lastPart')
的字符"-"
和 Session.get('lastPart')
字符"_"
。 If this is true, than please console.log('One element contains both parts')
. 如果是这样,则请
console.log('One element contains both parts')
。
I thought about $regex
, but don´t know the right syntax. 我考虑过
$regex
,但是不知道正确的语法。 I need something like this: 我需要这样的东西:
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')
}
In this case, where the first variable holds "BD" and the second one holds "FH", the output should be console.log('One element contains both parts')
. 在这种情况下,第一个变量包含“ BD”,第二个变量包含“ FH”,输出应为
console.log('One element contains both parts')
。
Try this: 尝试这个:
...{"arrayElements": {$regex:val}...
Declare the string val beforehand as firstpart+"-.*_"+lastpart
. 预先将字符串val声明为
firstpart+"-.*_"+lastpart
。 You didn't clarify if your two variables have the - and _ in them, so I assumed they don't. 您没有弄清楚两个变量中是否包含-和_,因此我认为它们没有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.