mario_nsport
mario_nsport

Reputation: 160

Find by the first characters of a string with a variable mongodb, nodejs

I want to find a document in my mongodb database by the first characters.

I have a string in my document like this:

name: 'Georges'

This name is generate just before but it can be too long until 16MB ! So its too long to do a find on a string of 16 MB. So I have the name in a variable

var name = 'Georges'

I do a insert in my database. And I want to find it with the characters. For example :

  var query = {name: /^Geo/};
  res = await db.collection('people').find(query).toArray());

And its works like that but I want this :

var first = 'Geo';
var query = {name: /^first/};
res = await db.collection('people').find(query).toArray());

But it cant work because its a variable, not a string.

Thanks in advance

Upvotes: 0

Views: 649

Answers (1)

YuTing
YuTing

Reputation: 6629

Use RegExp

var first = 'Geo';
var regex = new RegExp("^" + first, "g");
var query = {name: regex};

Upvotes: 1

Related Questions