Please help me. I have a collection as below
[
{
"_id":{
"$oid":"62a3673660e2f16c7a7bc088"
},
"merchant":{
"$oid":"62a3640560e2f16c7a7bc078"
},
"title":"24 Test 1",
"filter_conditions":{
"city":[
"AAA",
"BBB",
"CCC",
"DDD"
],
"state":[
],
"pincode":[
"12345"
]
}
},
{
"_id":{
"$oid":"62a3673660e2f16c7a7bc089"
},
"merchant":{
"$oid":"62a3640560e2f16c7a7bc079"
},
"title":"24 Test 2",
"filter_conditions":{
"city":[
"AAA",
"BBB"
]
}
}
]
I want to filter data based on pincode/city/state
if pincode is present match it and ignore city and state
elseif city is present match it and ignore state
else match on state
2
Answers
You can use an aggregation pipeline with a
$filter
:$filter
to grade the docs, so the grade for matchingpincode
is 100, for matchingcity
is 10 for matchingstate
is 1. Use$max
to keep the best grade only.See how it works on the playground example
You can work with nested
$cond
to perform the filtering.Concept:
Check
filter_conditions.pincode
is existed.1.1. If true, check the value is existed in
filter_conditions.pincode
array.1.2. Else, proceed to 2.
Check
filter_conditions.city
is existed.2.1. If true, check the value is existed in
filter_conditions.city
array.2.2. Else, proceed to 3.
Check if value is existed in
filter_conditions.state
array (default as empty array if the array is not existed).Sample Mongo Playground