I have a collection in MongoDB which looks like this:
{
"_id" : "ABCDEFGHIJK",
"content" : {
"arrayElements" : [
"BD-cacf99afd87bd536da0162b2246f415e_FH",
"BD-zhdfcf0bqa12qfT7jl10p9b3276o123p_HUCL",
"WPG-bklcf10bqa12qg64jl99p9b3276o576a_HUCL",
"EC-tzlscq10bqa12qg64jl19p9b3475o5z7_FH"
],
...
}
}
Additionally, I have two variables (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 "_"
. If this is true, than please console.log('One element contains both parts')
.
I thought about $regex
, but don´t know the right syntax. 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')
.
Try this:
...{"arrayElements": {$regex:val}...
Declare the string val beforehand as firstpart+"-.*_"+lastpart
. You didn't clarify if your two variables have the - and _ in them, so I assumed they don't.
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.