Count of records by Date MongoDB

后端 未结 2 774
花落未央
花落未央 2021-01-12 08:03

Here\'s a record Customers Collection

 {
    name: xyz,
    .
    .
    .
    createdAt: Sun Nov 20 2016 00:00:00 GMT+0530 (IST)
    lastModified: Sat Dec 10         


        
相关标签:
2条回答
  • 2021-01-12 08:37

    if you want to count by lastModified date and time then can use just like:

    db.getCollection('collectionName').aggregate({$group:{_id: "$lastModified", count:{$sum:1}}})
    

    and if you want to count by lastModified date only then can use just like:

    db.getCollection('collectionName').aggregate(
    [
        {
            $group:
            {
                _id:
                {
                    day: { $dayOfMonth: "$lastModified" },
                    month: { $month: "$lastModified" }, 
                    year: { $year: "$lastModified" }
                }, 
                count: { $sum:1 },
                date: { $first: "$lastModified" }
            }
        },
        {
            $project:
            {
                date:
                {
                    $dateToString: { format: "%Y-%m-%d", date: "$date" }
                },
                count: 1,
                _id: 0
            }
        }
    ])
    
    0 讨论(0)
  • 2021-01-12 08:37

    I got this sorted in yii2 by this

    $aggregateResult = Yii::$app->mongodb->getCollection('patient')->aggregate([
                [
                    '$match' => [
                        '$and' => [
                            ['deleted_at' => ['$exists' =>  false]],
                            ['registration_date' => ['$gte' =>  $startDateStamp, '$lte' => $endDateStamp]],
                        ]
                    ]
                ],
                [
                    '$group' => [
                        '_id' =>  [
                            'day' => ['$dayOfMonth' =>  ['$toDate' => ['$multiply' => ['$registration_date', 1000]]]],
                            'month' => ['$month' => ['$toDate' => ['$multiply' => ['$registration_date', 1000]]]],
                            'year' => ['$year' => ['$toDate' => ['$multiply' => ['$registration_date', 1000]]]]
                        ],
                        'count' => ['$sum' => 1],
                        'date' => ['$first' => ['$toDate' => ['$multiply' => ['$registration_date', 1000]]]]
                    ]
                ],
    
                [
                    '$project' => [
                        'date' => ['$dateToString' => ['format' => '%Y-%m-%d', 'date' => '$date']],
                        'count' => 1,
                        '_id' => 0
                    ]
                ],
                ['$sort' => ['date' => 1]],
    
            ]);
    
    0 讨论(0)
提交回复
热议问题