I'm facing issues while querying a MongoDB collection with documents containing nested array fields. Each document represents a product and includes an array called add_ons containing additional product information.
Here's an example of the document structure in Mongo:
I want to query documents where the productName matches a given input, the add_ons array contains an object with a specific addon_name, and the storeid matches a certain value.
Here's the code I'm currently using:
{
"parent": {
"$regex": "{{ textInput9.value }}",
"$options": "i"
},
"add_ons.addon_name": {
"$regex": "^{{ select2.selectedItem.addon_name }}$",
"$options": "i"
},
"storeid": "{{ storeIDs.value }}"
}
Will appreciate your feedback.
Just figured it out. I changed add $elemMatch and it somehow did the trick
-
"productName": { "$regex": "{{ textInput9.value }}", "$options": "i" } filters documents where the productName matches the provided text input.
-
"add_ons": { "$elemMatch": { ... } } is used to match documents where at least one item in the add_ons array matches the specified conditions within the nested $elemMatch object.
-
"addon_name": { "$regex": "^{{ select2.selectedItem.addon_name }}$", "$options": "i" } filters the add_ons array elements to find those where the addon_name matches the selected addon name.
-
"storeid": "{{ storeIDs.value }}" filters based on the specified storeid.
{
"productName": {
"$regex": "{{ textInput9.value }}",
"$options": "i"
},
"add_ons": {
"$elemMatch": {
"addon_name": {
"$regex": "^{{ select2.selectedItem.addon_name }}$",
"$options": "i"
}
}
},
"storeid": "{{ storeIDs.value }}"
}
1 Like