在previous post中,我问过如何按MongoDB中的数组元素对文档进行排序。
现在我必须在结果中过滤元素。特别是我想要排除不必要的字段。我找到了$filter函数,但仅适用于3.2以上的MongoDB版本
这里的例子是
样品采集
[
{
"_id":ObjectId("5695128ee4b04403440b61c2"),
"_class":"com.acme.entity.Company",
"name":"Company Name A",
"countries":[
{
"country_code":"a.b.c",
"country_name":"Italy",
"country_weight":4
},
{
"country_code":"b.c.d",
"country_name":"Germany",
"country_weight":4
},
{
"country_code":"c.d.e",
"country_name":"France",
"country_weight":3
}
]
},
{
"_id":ObjectId("292829287293bcbe440b22bb"),
"_class":"com.acme.entity.Company",
"name":"Company Name B",
"countries":[
{
"country_code":"a.b.c",
"country_name":"Italy",
"country_weight":6
}
]
},
{
"_id":ObjectId("99922222bbeecc3339900000"),
"_class":"com.acme.entity.Company",
"name":"Company Name C",
"countries":[
{
"country_code":"a.b.c",
"country_name":"Italy",
"country_weight":9
},
{
"country_code":"c.d.e",
"country_name":"France",
"country_weight":3
},
{
"country_code":"l.h.i",
"country_name":"Holland",
"country_weight":8
},
{
"country_code":"e.n.g",
"country_name":"England",
"country_weight":1
}
]
}
]
根据country_weight字段过滤和排序数据的查询
db.companies.aggregate([
{ $match: { "countries.country_code": "a.b.c"}},
{ $project: {
name : 1,
countries: "$countries",
aggregatefunction: {
$setDifference: [
{ $map: {
"input": "$countries",
"as": "p",
"in": { $cond: [
{ "$eq": [ "$$p.country_code", "$01.01.01" ] },
"$$p",
false
]}
}},
[false]
]
}
}},
{ $sort: { "countries.country_weight": -1 } }
])
通过这个解决方案,我进入了所有公司所在国家/地区。我想过滤国家/地区字段以仅获取已过滤的国家/地区。