ENV
ENV

Reputation: 1282

How to use partial match when using Mongo find javascript?

The following line of javascript code finds all devices from a defined Mongo collection Devices with error codes 210 or 220

const devices = await Devices.find({"ErrorCode": { "$in": ["210", "220"] }});

How would I be able to retrieve all devices with ErrorCodes containing 210 or 220 as a substring. Consider a device with error code: "Error: 210". I also want to retrieve that device.

Thanks! Any help would be appreciated!

Sample Document:

{
    "DeviceId" : "1234567890",
    "Status" : "ONLINE",
    "ErrorMessage" : "Error Code: 220 Error Message: Duplicate found",
    "Code" : "Error Code: 220",
}

Upvotes: 1

Views: 41

Answers (1)

turivishal
turivishal

Reputation: 36114

Try regular expression, added 3 ways,

1) $regex with $or:

You can try $regex regular expression operator with $or condition

const devices = await Devices.find({
  $or: [
    { Code: { $regex: "210" } },
    { Code: { $regex: "220" } }
  ]
});

Playground


2) new RegExp:

const devices = await Devices.find({
  Code: {
    $in: [new RegExp("210"), new RegExp("220")]
  }
});

3) / slash:

const devices = await Devices.find({
  Code: {
    $in: [/210/, /220/] // without double quotes
  }
});

Upvotes: 1

Related Questions