Mani
Mani

Reputation: 2563

Mongodb partial number search

I have the following query, every filter except the chartId of dataType Number is working fine. My chartId field contains data like 10000234. What I want to achieve is that when I enter 1000 or 234 it must return user with that chartId. Any help will be greatly appreciated.

const matchNames = {
  $or: [
    { 'userId.firstName': { $regex: term, $options: 'i' } },
    { 'userId.lastName': { $regex: term, $options: 'i' } },
    { 'userId.email': { $regex: term, $options: 'i' } },
    { 'userId.phoneNumber': { $regex: term, $options: 'i' } },
    { 'userId.chartId': { $regex: Number(term) } },
  ],
};

let aggregateDataQuery = [
  {
    $lookup: {
      from: 'users',
      localField: 'userId',
      foreignField: '_id',
      as: 'userId',
    },
  },
  { $match: { ...matchNames } }
]

Upvotes: 1

Views: 792

Answers (1)

turivishal
turivishal

Reputation: 36114

There is no straight way to do this, You can use $regexMatch operator to match the regular expression in internal fields,

  • $toString to convert chartId from number to string
  • $regexMatch to match input term it will return true / false
const matchNames = {
  $or: [
    { 'userId.firstName': { $regex: term, $options: 'i' } },
    { 'userId.lastName': { $regex: term, $options: 'i' } },
    { 'userId.email': { $regex: term, $options: 'i' } },
    { 'userId.phoneNumber': { $regex: term, $options: 'i' } },
    {
      '$expr': {
        '$regexMatch': {
          'input': { '$toString': { '$toLong': "$userId.chartId" } },
          'regex': term
        }
      }
    }
  ],
};

Playground

Upvotes: 1

Related Questions