首页 文章

如何在mongoDB中分组并返回结果中的所有字段

提问于
浏览
3

我在mongoDB中使用聚合方法进行分组,但是当我使用$ group时,它返回我用来分组的唯一字段 . 我尝试了$ project但它也没有用 . 我也尝试了$ first并且它有效,但结果数据现在采用不同的格式 . 这是我想要的响应格式 .

{ "_id" : ObjectId("5b814b2852d47e00514d6a09"), "tags" : [], "name" : "name here", "rating" : "123456789" }

在我的query.response中添加$ group之后,_id的值会发生变化 . (并且$ group只占用_id,如果我尝试任何其他关键字,它会抛出累加器的错误 . 请解释一下 . )

{
    "_id" :"name here" //the value of _id changed to the name field which i used in $group condition

}

我必须删除名称字段中的重复项,而不更改任何结构和字段 . 我也在使用带有mongoose的nodeJS,所以请提供适合它的解决方案 .

3 回答

  • 3

    您可以使用以下聚合查询 .

    $$ROOT 保持每个名称的整个文档后跟 $replaceRoot 将文档提升到顶部 .

    db.col.aggregate([
      {"$group":{"_id":"$name","doc":{"$first":"$$ROOT"}}},
      {"$replaceRoot":{"newRoot":"$doc"}}
    ])
    
  • 2

    当您在任何数据库上对数据进行分组时,这意味着您希望在必填字段上执行累积操作,而在累积操作中不包括的其他字段将在组中使用

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

    这里的_id对象将包含你想要保存的所有其他字段 .

    对于您的数据,您可以试试这个

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

    You can use this query

    db.col.aggregate([
                            {"$group" : {"_id" : "$name","data" : {"$first" : "$$ROOT"}}},
                            {"$project" : {
                                "tags" : "$data.tags",
                                "name" : "$data.name",
                                "rating" : "$data.rating",
                                "_id" : "$data._id"
                                }
                            }])
    

相关问题