Search code examples
node.jsmongodbmongoosemongodb-query

Compare numbers stored as string in MongoDB


I want to retrieve the persons whose experience is less than 5 and greater than 1. My Schema looks like

let person = new schema({
    isCompleted: { type: Boolean, default: false },
    candidateId: { type: String },
    firstName: { type: String },
    lastName: { type: String },
    mobile: { type: String },
    emailId: { type: String },
    gender: { type: String },
    phone: { type: String },
    secondaryEmail: { type: String },
    parentId: { type: String },
    totalExperience: { type: String },
    relevantExperience: { type: String },
    website: { type: String },
    skypeId: { type: String },
    additionalInfo: { type: String },
    street: { type: String },
    zipCode: { type: String },
    city: { type: String },
    state: { type: String },
    country: { type: String },
    photo: { type: String },
    isActive: { type: Boolean, default: true },
    isDeleted: { type: Boolean, default: false },
}

I have written a query like this.

let data = await Persons.find(
{"$expr" : {
    "$gte" : [{"$toDouble" :"$totalExperience"} , 1],
    "$lte" : [{"$toDouble" :"$totalExperience"} , 5]}})
.sort(dynamic.sort)
.skip(dynamic.skip)
.limit(dynamic.pageSize)
.select(dynamic.projection)
.populate(dynamic.populate);

But I am getting error MongoServerError: Failed to parse number '' in $convert with no onError value: Empty string

I am having null or '' data in my db. That's where I am getting this error. So I have written another query.

let data = await Persons.find({$expr: {
            $and: [
              {
                totalExperience:{ $exists: true, $nin: [null, ''] }
              },
              {
                $lte: [
                  {
                    $toDouble: "$totalExperience"
                  },
                  5
                ]
              },
              {
                $gte: [
                  {
                    $toDouble: "$totalExperience"
                  },
                  1
                ]
              }
            ]
          }
        });

But again I am getting this error MongoServerError: Unrecognized expression '$exists'

Can any one explain me how can I solve this problem. Thanks in Advance!


Solution

  • {
      $expr: {
        $and: [
          {
            $not: {$in: ["$totalExperience",["","test"]]}
          },
          {
            $gte: [{$toDouble: "$totalExperience"},1]
          },
          {
            $lte: [{$toDouble: "$totalExperience"},5]
          }
        ]
      }
    }