How to access embeded documents using aggregation

2019-09-06 18:51发布

问题:

This question already has an answer here:

  • Sum in nested document MongoDB 2 answers
db.logdata.findOne()
{
    "_id" : ObjectId("552cfc949258ff1fa8686f1a"),

    "ldl_date" : "2015-04-09",

    "ldl_mmo_id" : 5,

    "ldl_master_info_id" : 11,

    "ldl_publication_info_id" : 41616,

    "detail" : [

        {
            "ldl_id" : 54261629,

            "ldl_xml_info_id" : 37437691,

            "ldl_distribution_id" : 3289,

            "ldl_local_flag" : 1,

            "ldl_ftp_flag" : 0,

            "ldl_time" : "2015-04-09 06:36:46"
        }

    ]

}

I need to access the ldl_local_flag and count of the ldl_local_flag I tried following query but not get the exact result.

The query is

db.logdata.aggregate([
    {
    $group: {
        _id: "$ldl_mmo_id",
        total: {
            $sum: "$detail.ldl_local_flag"
        }
    }
    },
    {
    $limit: 10
    }
])

And output is

{ "_id" : 1, "total" : 0 }

{ "_id" : 2, "total" : 0 }

{ "_id" : 3, "total" : 0 }

{ "_id" : 4, "total" : 0 }

{ "_id" : 5, "total" : 0 }

please help me..........

回答1:

This might be helpful to you:

    db.collection.aggregate({
  $unwind: '$detail'
},
{
  $group: {
    "_id": "$detail.ldl_local_flag",
    "sum": {
      "$sum": "$detail.ldl_local_flag"
    }
  }
},
{
  $project: {
    "local_flags": "$_id",
     "count": "$sum"
  }
})