My document would look like this:
_id:123
configuration:{
date: 2020-10-01,
areas:[a,b,c]
conditions: {
'cond1': { 'logic': 1, 'value': 555 },
'cond2': { 'logic': 0, 'value': 55 },
'cond3': {
'sub-cond1': 444,
'logic': 1,
'second-line': 'abc',
'sub-cond-2': 1231
},
'cond4': { 'logic': -1, 'value': 1414 },
'cond5': { 'logic': 0, 'value': 55 },
'cond6': { 'logic': 1, 'value': 66 }
},
}
results:[result1,result2,result3]
I want to check if the sub-key called conditions
in the document has value exactly match all of the values as shown below and return the result:
query = {
'cond1': { 'logic': 1, 'value': 555 },
'cond2': { 'logic': 0, 'value': 55 },
'cond3': {
'sub-cond1': 444,
'logic': 1,
'second-line': 'abc',
'sub-cond-2': 1231
},
'cond4': { 'logic': -1, 'value': 1414 },
'cond5': { 'logic': 0, 'value': 55 },
'cond6': { 'logic': 1, 'value': 66 }
},
const cursor = collection.find({"$where":collection.configuration.conditions==query})
my final result should be [result1,result2,result3]
I tried the following command and its not working, so how can I do that? Thanks, appreciate it.
CodePudding user response:
You will have to access the nested properties using the dot operator.
So instead of {"$where":collection.configuration.conditions==query}
, it should be
{
"$where": {
"configuration.conditions.cond1.value": 555,
"configuration.conditions.cond1.logic":1
//Other conditions come here
}
}
In order to construct the db query, you can iterate over the query variable and transform that into the above query format. A nested for of loop can help with it.
CodePudding user response:
Give this a try:
query = {
'configuration.conditions.cond1.logic': 1,
'configuration.conditions.cond1.value': 555,
'configuration.conditions.cond2.logic': 0,
'configuration.conditions.cond2.value': 55,
'configuration.conditions.cond3.sub-cond1': 444,
'configuration.conditions.cond3.logic': 1,
'configuration.conditions.cond3.second-line': 'abc',
'configuration.conditions.cond3.sub-cond-2': 1231
'configuration.conditions.cond4.logic': -1,
'configuration.conditions.cond4.value': 1414,
'configuration.conditions.cond5.logic': 0,
'configuration.conditions.cond5.value': 55 ,
'configuration.conditions.cond6.logic': 1,
'configuration.conditions.cond6.value': 66
},
const cursor = collection.find({"$where":collection.configuration.conditions==query})
While the above 'may work' - This type of approach does not take into consideration document model best practices. How you model your data is critical for database performance. I'd suggest you structure your conditions as an 'array' not a 'dictionary'. configration.conditions[{}], you can then use array operators and do some pretty fun stuff with the MDB aggregation framework.
https://docs.mongodb.com/manual/reference/operator/query/elemMatch/