简体   繁体   中英

How can i use multiple group stages in mongodb aggregate query

Mongo query fails to return any input in case, I increase the number of group stages in my query. Below is the snippet of the query which I am using,

.group({
    _id: "$date",
    count: {
        $sum: 1
    },

})
/*
.group({
    _id: "$joinDate",
    count: {
        $sum: 1
    },

})
.group({
    _id: "$applyDate",
    count: {
        $sum: 1
    },

})*/

You can do by the following way

yourModel.aggregate([ { $group : { _id : "$date" } } ] )

This might help you to solve your problem.

@CsAlkemy, It is because the fields you are trying to use are not propagated after the $group stage.

For example, consider the following sample document and an aggregate query on the document,

{
    "name": "SV",
    "age": 21,
    "school": "KV",
    "city": "Ajmer"
}

Aggregate Query

db.temp.aggregate([
{
    $group: {
        "_id": "$school",
        "count": {
            $sum: 1
        }
    }
}])

Output

{ "_id" : "KV", "count" : 1 }

As you can see the fields which we get are only _id and count and the other fields name, age, school and city are lost and can't be used later.

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