简体   繁体   中英

Write mongodb query using Count , DISTINCT & SUM for the following scenario

mysql :

SELECT COUNT(DISTINCT col1, col2) AS 'aggCol1',
SUM(col3 = "2016-03-04 00:00:00" AND col5 = 29) AS 'aggCol2' 
FROM table1 
WHERE col4 = 50;

I want to write the query on MongoDB.

You can use Aggregation Framework:

To filter by col4 you should use $match

To transform your collection into single result you need $group with _id set to null

To get distinct values for col1 and col2 you can use $addToSet

To use nested filtering for col3 and col5 you need $filter

To get array length you can use $size

So entire aggregation should look like this:

db.col.aggregate([
    {
        $match: { col4: 50 }
    },
    {
        $group: {
            _id: null,
            c12: { $addToSet: { col1: "$col1", col2: "$col2" } },
            c3: { $push: { col3: "$col3", col5: "$col5" } }
        }
    },
    {
       $project: {
            c12: 1,
            c3: {
               $filter: {
                  input: "$c3",
                  as: "item",
                  cond: { $and: [
                    { $eq: [ "$$item.col3", ISODate("2016-03-04") ] },
                    { $eq: [ "$$item.col5", 29 ] }
                  ] }
                }
            }
        }
    },
    {
        $project: {
            aggCol1: { $size: "$c12" },
            aggCol2: { $size: "$c3" }
        }
    }
])

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