简体   繁体   中英

Count and Update nested array in mongodb

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM