how to group in mongoDB and return all fields in result

后端 未结 5 585
梦如初夏
梦如初夏 2020-12-30 04:07

I am using aggregate method in mongoDB to group but when I use $group it returns the only field which I used to group. I have tried $project but it

5条回答
  •  悲哀的现实
    2020-12-30 05:08

    When you group data on any database, it means you want to perform accumulated operation on the required field and the other field which will not be include in accumulated operation will be used in group like

     db.collection.aggregate([{
     $group: {
       _id: { field1: "", field1: "" },
       acc: { $sum: 1 }
     }}]
    

    here in _id object will contains all other fields which you want to hold.

    for your data you can try this

    db.collection.aggregate([{
        $group: {
            _id: "$name",
            rating: { $first: "$rating" },
            tags: { $first: "$tag" },
            docid: { $first: "$_id" }
        }
    },
    {
        $project: {
            _id: "$docid",
            name: "$_id",
            rating: 1,
            tags: 1
        }
    }])
    

提交回复
热议问题