dan-3
dan-3

Reputation: 73

Counting this in mongodb

I have a collection called orders in the main database. To count all the orders, I type

use main
db.orders.count()

All the orders documents have the customer_email_address. Each customers can have many orders.

How can I count all unique email addresses?

Also, how can I count all unique email addresses that are NOT in a list of a few particular email addresses like [email protected] and [email protected] (Me and my coworkers have placed some test orders and we'd like to ignore those.)

Upvotes: 0

Views: 70

Answers (1)

zero323
zero323

Reputation: 330203

You can use simple distinct with query

db.orders.distinct(
    'customer_email_address',
    {customer_email_address:
        {$nin: ["[email protected]", "[email protected]"]}
    }
).length

With aggregation framework:

pipeline = [
    {
        "$match" : {
            "customer_email_address" : {
                "$nin" : [
                    "[email protected]",
                    "[email protected]"
                ]
            }
        }
    },
    {
        "$group" : {
            "_id" : "$customer_email_address",
            "count" : {
                "$sum" : 1
            }
        }
    },
    {
        "$group" : {
            "_id" : null,
            "count" : {
                "$sum" : 1
            }
        }
    }
]
db.orders.aggregate(pipeline).result[0].count

Upvotes: 1

Related Questions