Home > database >  MongoDB: aggregate Statis Key value and Total count
MongoDB: aggregate Statis Key value and Total count

Time:05-27

I have a data with total counts. But i need Statis object and Totoal Counts.

My sample data

{
    "_id" : ObjectId("6218b5f0405919280c209f73"),
    "inspectionResult" : "Passed",
    "projectId" : ObjectId("6218a31f405919280c209e18"),
    "accountId" : ObjectId("621888e852bd8836c04b8f82"),
    "dateInspected" : ISODate("2022-03-08T00:00:00.000Z"),
}

My Aggegate query

db.getCollection('welds').aggregate([
    {
        $match: {
            accountId: ObjectId("621888e852bd8836c04b8f82"),
            projectId: ObjectId("6227089af6d4162e9c57d8be"),
        }
    },
    {
        $facet: {
            'PostWeldInspection': [
                {
                    $project: {
                        _id: 0,
                        x: 'PWI',
                        dateInsp: '$dateInspected',
                    }
                },
                { $count:  'Y' }
            ],
        }
    }
])

My result:

{
    "PostWeldInspection" : [ 
        {
            "Y" : 62
        }
    ]
}

But i need static object and total count Like below,

{
    "PostWeldInspection" : [ 
        {
            "x" : "PWI",
            "Y" : 62
        }
    ]
}

Thanks in advance.

CodePudding user response:

This is just the $count stage behavior, you can just use a $group stage instead to preserve other fields. The docs also specify this is equivalent:

The $count stage is equivalent to a $group $project sequence:

db.collection.aggregate([
  {
    $match: {
      accountId: ObjectId("621888e852bd8836c04b8f82"),
      projectId: ObjectId("6227089af6d4162e9c57d8be"),
      
    }
  },
  {
    $facet: {
      "PostWeldInspection": [
        {
          $project: {
            _id: 0,
            x: "PWI",
            dateInsp: "$dateInspected",
            
          }
        },
        {
          $group: {
            _id: null,
            x: {
              $first: "$x"
            },
            dateInsp: {
              $first: "$dateInsp"
            },
            Y: {
              $sum: 1
            }
          }
        },
        {
          $project: {
            _id: 0,
            
          }
        }
      ],
      
    }
  }
])

Mongo Playground

I recommend using this simplified version as I'm not sure why you incorporated $facet into your pipeline.

  • Related