MongoDB Regular Expression Search - Starts with using javascript driver and NodeJS

后端 未结 2 1239
-上瘾入骨i
-上瘾入骨i 2020-12-03 14:53

I\'m using the JavaScript mongodb driver from nodejs. I want to do this query in my JavaScript function:

db.mycollection.find({Zip:/^94404/}); 
2条回答
  •  渐次进展
    2020-12-03 15:39

    You almost have it. You keep ending up with a regex inside a string and looking for the string '/^94404/' going to find anything unless you have some strange looking zip codes.

    The easiest way to build a regex object from a string in JavaScript is to use new RegExp(...):

    var query = { Zip: new RegExp('^' + zipCode) };
    

    Then you can:

    collection.find(query).toArray(...)
    

    That sort of thing works in the MongoDB shell and similar things work in the Ruby interface so it should work in the JavaScript interface as well.

提交回复
热议问题