首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mongo在聚合请求中按对象组织

Mongo在聚合请求中按对象组织
EN

Stack Overflow用户
提问于 2022-10-23 10:47:01
回答 1查看 41关注 0票数 0

我的项目是在nodeJs和快递,我使用猫鼬对我的数据库mongoDb的请求。

我有一个Media模型,它的结构是:

代码语言:javascript
复制
{
  "_id": {
    "$oid": "6354f982a11464ff4f7bac60"
  },
  "userId": {
    "$oid": "6353aa119d39ccbb3263123f"
  },
  "date": "2022-10-23",
  "base64": "data:image/png;base64,iVBORw0KGgoAAA....=",
  "label": "Noamount",
  "uriPath": "xxxx",
  "s3Path": "xxxx",
  "amount": 0,
  "__v": 0,
  "type": "tva"
}

就像你看到的,有一个现场约会,想象一下,我有三个媒体在不同的月份:

代码语言:javascript
复制
{
  "date": "2022-10-23",
  "label": "monthTen",
  "type" : "tva",
  ... // Other property
},
{
  "date": "2022-09-10",
  "label": "monthNineFirst",
  "type" : "tva",
  ... // Other property
},
{
  "date": "2022-09-19",
  "label": "monthNineSecond",
  "type" : "other",
  ... // Other property
}

我想输出这样的内容:

代码语言:javascript
复制
// Ordery by type in first place and by month
// number like 9 = the month inside the date property
{
  tva: {
   9: [{ label: "monthNineFirst"... }],
   10: [{ label: "monthNineTen"... }]
  },
  other: {
   9: [{ label: "monthNineSecond"... }]
  }
}

找到属性aggregate,但我没有正确理解它。

我知道如何在JS中进行测试,这很容易,但是我可以直接在属性aggregate$group的请求下这样做吗?

到目前为止,我已经做了一些https://mongoplayground.net/p/-vAbdnnqOfD

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-23 12:12:22

这里有一种方法可以通过扩展mongoplayground.net启动来实现。

代码语言:javascript
复制
db.collection.aggregate([
  { // group all docs by month
    $group: {
      _id: {
        $month: {
          $dateFromString: {
            dateString: "$date",
            format: "%Y-%m-%d"
          }
        }
      },
      data: {"$push": "$$ROOT"}
    }
  },
  { // group all groups into a single doc
    "$group": {
      "_id": null,
      "groupData": {
        "$push": {
          // k,v for $arrayToObject
          "k": "$_id",
          "v": {
            "$sortArray": {
              "input": "$data",
              "sortBy": {"date": 1}
            }
          }
        }
      }
    }
  },
  {
    "$replaceWith": {
      "$arrayToObject": {
        "$map": {
          "input": {
            // sort by month
            "$sortArray": {
              "input": "$groupData",
              "sortBy": {"k": 1}
            }
          },
          "in": {
            "$mergeObjects": [
              "$$this",
              { // rewrite k as string
                "k": {"$toString": "$$this.k"}
              }
            ]
          }
        }
      }
    }
  }
])

mongoplayground.net上试一试。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74170517

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档