Newbie Dev
Newbie Dev

Reputation: 69

MongoDB - Find numbers that starts with a string

I'm trying to make a query that gets all the prices that starts with '12'. I have a collection like this:

{
  "place": "Costa Rica", 
  "name": "Villa Lapas",
  "price": 1353,
},
{
  "place": "Costa Rica", 
  "name": "Hotel NWS",
  "price": 1948,
},
{
  "place": "Costa Rica", 
  "name": "Hotel Papaya",
  "price": 1283,
},
{
 "place": "Costa Rica", 
 "name": "Hostal Serine",
 "price": 1248,
},

And I want my results like this:

 {
  'prices': [
      1248,
      1283
   ]
 }

I'm converting all the prices to string in order to use a regex function. But I don't understand very well how to use the regex in my query. My query returns:

{ "prices" : null }
{ "prices" : null }

Could someone please guide me? :)

db.collection.aggregate([
  {'$project': {
      '_id': 0,
      'price': {'$toString': '$price'}
  }},
  {'$project': {
      'prices': {'$regexFind': { 'input': "$price", 'regex': '^12' }}
  }}
]).pretty();

Upvotes: 0

Views: 2381

Answers (1)

Gibbs
Gibbs

Reputation: 22974

You are almost correct.

db.test.aggregate([
  {'$project': {
      '_id': 0,
      'prices': {'$toString': '$price'}
          ^^^ -> I meant this
  }},
  {'$match': {
      'prices': {'$regex': '^12' }
          ^^^ -> same here
  }}
])

You need to use $match with $regex which yields the result as you expected.

If you use regexFind, it works on all matching docs and returns null where input doesn't match the pattern

And

In the first project you have price instead prices. If you refer the first project name in the second project, then pipeline matches.

Upvotes: 1

Related Questions