我有以下数据:
{
"Name": "Test"
"Location": "Whatever",
"customerServices": [
{
"id": "test",
"cusId": "test",
"adr": "Adr 1",
"serviceCounty": "Center",
"area": "village"
},
{
"id": "test",
"cusId": "test",
"adr": "adr2",
"serviceCounty": "West",
"area": "city"
},
{
"id": "test",
"cusId": "test",
"adr": "test",
"serviceCounty": "West",
}
]
}
我需要检查元素数组(customerServices字段),然后过滤它。我必须检查每个元素是否有以下3个键:
- adr
- serviceCounty <
- 区域/gh>
如果缺少这些键中的任何一个,则应该完全排除数组中的该项。所以这个例子中的最终结果是:
{
"Name": "Test"
"Location": "Whatever",
"customerServices": [...],
"filteredCustomerServices": [
{
"id": "test",
"cusId": "test",
"adr": "Adr 1",
"serviceCounty": "Center",
"area": "village"
},
{
"id": "test",
"cusId": "test",
"adr": "adr2",
"serviceCounty": "West",
"area": "city"
}
]
}
你可以看到最后一项被排除,因为它有'area'键缺失。有什么办法吗?我真的很喜欢这个mongo聚合主题。
试试这个:
db.yourCollectionName.aggregate([
{
$unwind: "$customerServices"
},
{
$addFields: {
"customerServices.skip": {
$and: [
{ $ifNull: ["$customerServices.adr", false] },
{ $ifNull: ["$customerServices.serviceCounty", false] },
{ $ifNull: ["$customerServices.area", false] }
]
}
}
},
{
$match: {
"customerServices.skip": { $ne: false }
}
},
{
$group: {
_id: "$_id",
Name: { $first: "$Name" },
Location: { $first: "$Location" },
filteredCustomerServices: {
$push: "$customerServices"
}
}
}
])