Sweta Sharma
Sweta Sharma

Reputation: 483

how to modify the value without updating it and then matching it with the element in mongodb?

I have an element which whose value I am getting dynamically to match. The only difference is the value in DB is concatenated with an underscore and the value I am getting is without underscore. So is there any way to modify the value according to what I am getting and apply "find".

Collection:

    "name": {
      "age": 23,
      "firstname": "sweta",
      "secondname": "sharma"},
      "hobbyImages": [
         0: "0_abc_0.jpg",
         1: "1_def_1.jpg"
      ]
    }

Query:

db.find({ "name.age": 23, "hobbyImages": imageName });

I am having an image name as abc.jpg

Expected Result:

The collection which I have mentioned above but I am not getting anything. Does anyone have any idea how to remove the '_' and '0' and then check the element value?

Upvotes: 1

Views: 54

Answers (1)

Vasileios Pallas
Vasileios Pallas

Reputation: 4877

You can try match the image with $regex.

const [name, ex] = imageName.split('.');
const regex = new RegExp(`\\d_${name}_\\d.${ex}`, "gi")
db.users.find(
   { "name.age": 23, "hobbyImages": { "$elemMatch": { "$regex": regex } } }
)

Upvotes: 1

Related Questions