首页 > 解决方案 > 使用聚合从输入中获取数组

问题描述

我的输入文件如下所示:

[
    {
        "type" : "asdf",
        "properties" : {
            "Name" : "First center",
            "Code" : "ABCD",
            "Address" : "Emmastr 14",
            "City" : "Rotterdam",
            "Postcode" : 55968,
        }
    },
    {
        "type" : "qwer",
        "properties" : {
            "Name" : "Second center",
            "Code" : "OTHER",
            "Address" : "Havenstraat 15",
            "City" : "Rotterdam",
            "Postcode" : 88767,
        }
    },
    {
        "type" : "zxcv",
        "properties" : {
            "Name" : "Third center",
            "Code" : "ABCD",
            "Address" : "Kerkstraat 16",
            "City" : "Amsterdam",
            "Postcode" : 33948,
        }
    },
    {
        "type" : "tyiu",
        "properties" : {
            "Name" : "Fourth center",
            "Code" : "ABCD",
            "Address" : "Zeestraat 17",
            "City" : "Amsterdam",
            "Postcode" : 56475,
        }
    }
]

我的任务是按城市分组呈现这些信息(每个城市的文档)。只有具有的项目Code="ABCD"才会出现在输出中。输出应按城市名称 ( _id) 排序。输出应写入新集合。

所以我正在寻找的输出是这样的:

_id: "Amsterdam",
center: [
    {"Name": "Third center" , "Postcode": 33948, "Address": "Kerkstraat 16"},
    {"Name": "Fourth center" , "Postcode": 56475, "Address": "Zeestraat 17"}
]

_id: "Rotterdam",
center: [
    {"Name": "First center" , "Postcode": 55968, "Address": "Emmastr 14"}
]

这个小片段过滤器按“ABCD”,分组city并将输出写入新集合。

db.centers.aggregate ([
{$match: {"properties.Code": "ABCD"}}
,{ $group: {_id: "$properties.City"}}
,{ $out: "newColl"}
])

但由于缺乏实践经验,我并没有走得更远。我很难从输入中不是数组的东西中取出数组。有没有人可以帮忙?

标签: mongodb

解决方案


  • $push制作必填字段的数组
  • $sort_id升序排列
db.centers.aggregate([
  { $match: { "properties.Code": "ABCD" } },
  {
    $group: {
      _id: "$properties.City",
      center: {
        $push: {
          Name: "$properties.Name",
          Postcode: "$properties.Postcode",
          Address: "$properties.Address"
        }
      }
    }
  },
  { $sort: { _id: 1 } },
  { $out: "newColl" }
])

操场


推荐阅读