在mongodb中计算和更新嵌套数组

时间:2017-08-16 06:50:24

标签: arrays mongodb aggregate

我是使用mongo db的新手,并且一直试图找到一种方法来获取mongo db collection中嵌套数组的计数,如下所示。

    {
      city_id: 'C1',
      city_name: "C1Name",
      wards: [{
      ward_id: "W1",
      ward_number: "1",
      areas: [{
      area_id: "a1",
      area_name: "a1Name"
    },
    {
      area_id: "a2",
      area_name: "a2Name"
    }]
  }, 
  {
    ward_id: "W2",
    ward_number: "2",
    areas: [{
      area_id: "a21",
      area_name: "a21Name"
    }, {
      area_id: "a22",
      area_name: "a22Name"
    }]
  }]
},
    {
      city_id: 'C2',
      city_name: "C2Name",
      wards: [{
      ward_id: "W21",
      ward_number: "21",
      areas: [{
        area_id: "aw21",
        area_name: "aw21Name"
    },{
        area_id: "aw22",
        area_name: "aw22Name"
    }]
  },{
      ward_id: "W132",
      ward_number: "132",
      areas: [{
      area_id: "a132",
      area_name: "a132Name"
    }, {
      area_id: "a1332",
      area_name: "a2112Name"
    }]
  }]
}

现在我想在city_details中使用city_id = C1和ward_id = W1

的区域数量

我使用聚合作为

    db.city_details.aggregate(
      {$match:{"city_id":"C1"}},
      {$project:{"wards":"$wards"}},
      {$unwind:"$wards"},   
      {$project{"ward":"$wards.id","area":"$wards.areas"}},
      {$match:{ward:"W1"}},
      {$project:{$count:{"area"}}
    )

这应该算我2,但它不起作用。

另外,我如何更新这些区域阵列?

1 个答案:

答案 0 :(得分:0)

您的查询无效的原因是{$match:{ward:"W1"}}在上一个结果中找不到W1

运行{$match:{ward:"W1"}}之前的结果如下所示:

{
    "area" : [ 
        {
            "area_id" : "a1",
            "area_name" : "a1Name"
        }, 
        {
            "area_id" : "a2",
            "area_name" : "a2Name"
        }
    ]
},
{
    "area" : [ 
        {
            "area_id" : "a21",
            "area_name" : "a21Name"
        }, 
        {
            "area_id" : "a22",
            "area_name" : "a22Name"
        }
    ]
}

找不到W1

相反,你可以使用这样的查询:

db.city_details.aggregat([
  {$match: {"city_id": "C1"}},
  {$project: {"ward": {$filter: {"input": "$wards", "as": "ward", "cond": { $eq: ["$$ward.ward_id", "W1"]}}}}},
  {$unwind:"$ward"},
  {$project: {"size": {$size: "$ward.areas"}}}
])

关于你的第二个问题。这并不容易,this post将为您提供有关更新mongodb中嵌套数组的更多信息。