Home > Blockchain >  How to group documents in mongodb and project _id as different name?
How to group documents in mongodb and project _id as different name?

Time:04-01

db.getCollection("analytics").aggregate(
    [
        { 
            "$match" : { 
                "uID" : { 
                    "$in" : [
                        "202003008", 
                        "20200306"
                    ]
                }, 
                "midNightTimeStamp" : { 
                    "$gte" : ISODate("2022-03-26T18:30:00.000 0000")
                }
            }
        }, 
        { 
            "$group" : { 
                "_id" : "$midNightTimeStamp", 
                "energyConsumed" : { 
                    "$sum" : "$energyConsumed"
                }, 
            }
        }, 
        { 
            "$project" : { 
                "midNightTimeStamp" : 1.0, // I also want to project with a different name.
                "energyConsumed" : 1.0
            }
        }
    ], 
    { 
        "allowDiskUse" : false
    }
);

As shown in the above query I want to project a field as midNightTimeStamp which is same as _id (accumulator object) so that when I receive the documents, I get it something as

{
    midNightTimeStamp: ISODate("2022-03-26T18:30:00.000 0000"),
    energyConsumed: 100
}

CodePudding user response:

If I've understood correctly you only need to do this:

{
    "$project" : { 
        "_id": 0, // Not output the "real" _id
        "midNightTimeStamp" : "$_id", // output _id value with name "midNightTimeStamp"
        "energyConsumed" : 1.0
    }
}

Example here

CodePudding user response:

It can be achieved by adding a field in project stage as

"$project" : { 
                "_id" : 0.0, 
                "midNightTimeStamp" : "$_id", // This will be added.
                "energyConsumed" : 1.0
            }

Which will result to the following query:

db.getCollection("analytics").aggregate(
        [
            { 
                "$match" : { 
                    "uID" : { 
                        "$in" : [
                            "202003008", 
                            "20200306"
                        ]
                    }, 
                    "midNightTimeStamp" : { 
                        "$gte" : ISODate("2022-03-26T18:30:00.000 0000")
                    }
                }
            }, 
            { 
                "$group" : { 
                    "_id" : "$midNightTimeStamp", 
                    "energyConsumed" : { 
                        "$sum" : "$energyConsumed"
                    }
                }
            }, 
            { 
                "$project" : { 
                    "_id" : 0.0, 
                    "midNightTimeStamp" : "$_id", 
                    "energyConsumed" : 1.0
                }
            }
        ], 
        { 
            "allowDiskUse" : false
        }
    );
  • Related