mongodb - Two identical $regex declarations behave differently in Mongo shell -
according $regex documentation, following $regex declarations identical:
{ <field>: { $regex: /pattern/, $options: '<options>' } } { <field>: { $regex: 'pattern', $options: '<options>' } } { <field>: { $regex: /pattern/<options> } }
i playing around zips.json dataset in mongo shell, , tried find cities begin , end same character. however, query returned different results depending on whether used 'pattern'
or /pattern/
.
$ mongo mongodb shell version: 3.0.1 connecting to: test > db.version() 3.0.1 > db.zips.find( { city: { $regex: '^(.).*\1$' } }, { city: true } ).count() 0 > db.zips.find( { city: { $regex: /^(.).*\1$/ } }, { city: true } ).count() 1418
is there difference in behavior despite documentation says? latter being javascript regex perhaps?
silly me. in first declaration, should have escaped backslash this:
db.zips.find( { city: { $regex: '^(.).*\\1$' } }, { city: true } ).count()
Comments
Post a Comment