0

I am new to using mongo db and have been trying to figure out a way to get count of an nested array in mongo db collection which looks like follows.

    {
      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"
    }]
  }]
}

now here I want number of areas in city_details where city_id=C1 and ward_id=W1

I used aggregation as

    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"}}
    )

This should get me count as 2 but it isn't working.

Also how do I update these areas arrays ?

TGW
  • 805
  • 10
  • 27

1 Answers1

0

The reason your query doesn't work is because {$match:{ward:"W1"}} can't find W1 within the previous result.

The Result before running {$match:{ward:"W1"}} looks like this:

{
    "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"
        }
    ]
}

There is no W1 to find.

Instead you can use a query like this:

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"}}}
])

Regarding to your second question. It's not that easy, this post will give you more to read about updating nested arrays in mongodb.

  • Hii, thanks Julian your query did the job but I don't understand the use of two $ signs in the $eq operator – TGW Aug 16 '17 at 10:06
  • More details can be found in the [mongodb docu](https://docs.mongodb.com/manual/reference/aggregation-variables/). But in short, with _$$_ you can access the current value from _ward_. – Julian Hilbers Aug 16 '17 at 11:06