在集合中存在一个字段的条件匹配
请帮我。我有一个集合如下,
[
{
"_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"
]
}
}
]
我想根据Pincode/City/State过滤数据
。 Elseif City在这里匹配并忽略状态 否则匹配状态
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
$ filter
的聚合管道使用:$ filter
对文档进行评分,因此匹配的pincode
的等级为100,用于匹配city> city
是10的是10 /code>是1。使用$ max
仅保留最佳成绩。查看在 Playground示例示例
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
您可以使用嵌套
$ cond
来执行过滤。概念:
检查
filter_conditions.pincode
。1.1。如果为true,请在
filter_conditions.pincode
array中检查该值。1.2。否则,继续进行 2 。
检查
filter_conditions.city
。2.1。如果为true,请在
filter_conditions.city
array中检查该值。2.2。否则,继续进行 3 。
检查
filter_conditions.state
array中是否存在值(默认为空数组,如果不存在数组)。示例mongo playground
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