Like equivalent in mongo db and its syntax


#1

hi everyone,
i am trying to search a variable in my collection in Mongo db.
i am giving ids like 2001_1, 2001_2, 2001_3, 3001_1 , 3001_2,etc.
my variable(Lets say k1 ) will have the value of series, i am going to search .In this case it will be ‘2001’.
'
i need to search the total occurrence of 2001 series. i need to search ‘2001_’ total count .
i am stuck here from many hours and cant find anything . i am searching for any equivalent of ‘like’ that we use in mysql db.
i am writing a query like this.
k12 = 2001;
db.find({post_id: k12+/^_/}).count().
thanks in advance for those are going to put any effort.

ANSWER (this worked for me):
special thanks to @robfallows ’ for guiding me through this.
i made few changes in query and this works for me. Hope this could help others save their development time(i wasted a lot of time in this activity).

MyCollection.find({_id:{$regex:new RegExp(’^’ + k12)}});


#2

You could use a regex. I have to say this is not a great way to do what you’re trying to do. It would be better to use a composite index on multiple fields. However:

MyCollection.find({ _id: { $regex: `^${k12}_` } }).count();

or, if you prefer ES5 syntax:

MyCollection.find({ _id: { $regex: '^' + k12 + '_'  } }).count();

#3

To expand on what @robfallows was saying:

It would be more performant to use more than one property for this so that you can make an index that orders your series.

Example:

Instead of ids of 2001_01, 2001_02…

You could have { series: 2001, num: 1 }, { series: 2001, num: 2 } … { series: 3001, num: 1 }, which would be queried with .find({ series: 2001 }, { sort: { num: 1 } }) for an entire series, or .findOne({ series: 2001, num: 2 }) for an individual document. Much much more performant.