如何将组的结果添加到分组的文档中? MongoDB

How to add the results of a group, to the grouped documents? MongoDB

我正在通过传递这些数据来创建一些报告: Reports Model

userId : String,
marketId : String,
marketName : String,
itemId : String,
minPricePerKg : Number,
maxPricePerKg : Number

通过 POST 请求创建 3 份报告:

POST /reports 

request 1:
{
  "details": {
    "userId": "1",
    "marketId": "1",
    "marketName": "market1",
    "itemId": "1",
    "minPricePerKg": "10",
    "maxPricePerKg": "20",
  }
}

request 2:
{
  "details": {
    "userId": "2",
    "marketId": "1",
    "marketName": "market1",
    "itemId": "1",
    "minPricePerKg": "20",
    "maxPricePerKg": "40",
  }
}

request 3:
{
  "details": {
    "userId": "1",
    "marketId": "2",
    "marketName": "market2",
    "itemId": "1",
    "minPricePerKg": "80",
    "maxPricePerKg": "100",
  }
}

我想获得某些特定 itemId(从查询中收到)的所有报告的平均价格。 因此,为了便于理解,我们使用 itemId.. 使用 $match : { itemId }

过滤掉所有报告

请求时 GET /reports?itemId=1

Expected Output

[
  {
    "marketId": "1",
    "itemId": "1",
    "marketName": "market1",
    "users": ["1", "2"],
    "minPrice": 15,
    "maxPrice": 30
  },
  {
    "marketId": "2",
    "itemId": "1",
    "marketName": "market2",
    "users": ["1"],
    "minPrice": 80,
    "maxPrice": 100
  }
]

此处 minPrice 是所有 minPricePerKg 的平均值,maxPrice 是相应 marketId's 报告的所有 maxPricePerKg 的平均值。 我也想获得所有字段,即 (marketId, marketName, users, itemId) 结果


我得到的输出是:

[
  {
    "_id": {
      "marketId": "market1"
    },
    "minPrice": 15,
    "maxPrice": 30
  },
  {
    "_id": {
      "marketId": "market2"
    },
    "minPrice": 80,
    "maxPrice": 100
  }
]

我的方法是这样的:

const res = await Report.aggregate([
  { $match: { itemId } },
  { $group: { _id: { marketId : "$marketId" }, minPrice: { $avg: '$minPricePerKg' }, maxPrice: { $avg: '$maxPricePerKg' } } },
  { $project: { "marketName": 1 } },
]);

查询

  • 组保留组中共有的那些字段
  • 并积累那些不常见的usersMinPriceMaxPrice

Test code here

aggregate(
[{"$replaceRoot": {"newRoot": "$details"}},
  {"$group":  
    {"_id": 
      {"marketId": "$marketId",
        "itemId": "$itemId",
        "marketName": "$marketName"},
      "avgMinPrice": {"$avg": {"$toDouble": "$minPricePerKg"}},
      "avgMaxPrice": {"$avg": {"$toDouble": "$maxPricePerKg"}},
      "users": {"$push": "$userId"}}},
  {"$replaceRoot": {"newRoot": {"$mergeObjects": ["$_id", "$$ROOT"]}}},
  {"$project": {"_id": 0}}])