鉴于以下虚拟集合,我想为给定资源提取出口和进口国家:
[{
country: "France",
exchange: {
export: [{
resource: "MILK",
origin: ["Toulouse", "Bordeaux"]
}],
import: [{
resource: "BEEF",
origin: ["Lyon", "Marseille"]
}]
}
}, {
country: "Spain",
exchange: {
export: [{
resource: "PORK",
origin: ["Madrid", "Barcelona"]
}],
import: [{
resource: "MILK",
origin: ["Valencia", "Bilbao"]
}]
}
}]
预期结果:
{
resource: "MILK",
exportingCountries: ["France"],
importingCountries: ["Spain"]
}
我一直在和$group
一起玩,但是我找不到找到有条件地$addToSet
个国家/地区的方法。
答案 0 :(得分:1)
您可以使用$concatArrays组合exchange.export
和exchange.import
数组。这样一来,您可以country
来$group,然后需要使用$filter和$map运算符取回import
和export
,请尝试: / p>
db.col.aggregate([
{
$project: {
country: 1,
resources: {
$concatArrays: [
{ $map: { input: "$exchange.export", in: { resource: "$$this.resource", exchange: "export" } } },
{ $map: { input: "$exchange.import", in: { resource: "$$this.resource", exchange: "import" } } },
]
}
}
},
{
$unwind: "$resources"
},
{
$group: {
_id: "$resources.resource",
resources: { $addToSet: { country: "$country", exchange: "$resources.exchange" } }
}
},
{
$project: {
_id: 0,
resource: "$_id",
importingCountries: {
$map: {
input: { $filter: { input: "$resources", as: "r", cond: { $eq: [ "$$r.exchange", "import" ] } } },
in: "$$this.country"
}
},
exportingCountries: {
$map: {
input: { $filter: { input: "$resources", as: "r", cond: { $eq: [ "$$r.exchange", "export" ] } } },
in: "$$this.country"
}
}
}
}
])
输出:
{ "resource" : "PORK", "importingCountries" : [ ], "exportingCountries" : [ "Spain" ] }
{ "resource" : "BEEF", "importingCountries" : [ "France" ], "exportingCountries" : [ ] }
{ "resource" : "MILK", "importingCountries" : [ "Spain" ], "exportingCountries" : [ "France" ] }