首页 > 解决方案 > 在分组键上创建具有最少和最多计数的文档数组

问题描述

我有以下收藏

[
  {
    _id: {
      giftId: "coin",
      userId: "5b839dfeaaafc94ff323da35"
    },
    count: 1
  },
  {
    _id: {
      giftId: "coin",
      userId: "5b8390cc4bf35e13fe67d545"
    },
    count: 2
  },
  {
    _id: {
      giftId: "Gold",
      userId: "5b8390cc4bf35e13fe67d545"
    },
    count: 3
  },
  {
    _id: {
      giftId: "Gold",
      userId: "5b8390cc4be35e13fe67d545"
    },
    count: 1
  },
  {
    _id: {
      giftId: "Silver",
      userId: "5b8390cc4bf35e13fe67d545"
    },
    count: 4
  },
  {
    _id: {
      giftId: "Silver",
      userId: "5b8390cc4bf35e13ff67d545"
    },
    count: 2
  }
]

我需要以下输出

[{
    array1: [{
    _id: {
      giftId: "coin",
      userId: "5b8390cc4bf35e13fe67d545"
    },
    count: 2
  },
  {
    _id: {
      giftId: "Gold",
      userId: "5b8390cc4bf35e13fe67d545"
    },
    count: 3
  },
  {
    _id: {
      giftId: "Silver",
      userId: "5b8390cc4bf35e13fe67d545"
    },
    count: 4
  }],
    array2: [{
      _id: {
        giftId: "coin",
        userId: "5b839dfeaaafc94ff323da35"
      },
      count: 1
  }, {
    _id: {
      giftId: "Silver",
      userId: "5b8390cc4bf35e13ff67d545"
    },
    count: 2
      },{
    _id: {
      giftId: "Gold",
      userId: "5b8390cc4be35e13fe67d545"
    },
    count: 1
  }]
}]

giftId我需要对对象数组中的每个进行计数。假设在上面的文件中,giftId 硬币有 2 个计数,giftId 黄金有 3 个计数,giftId 白银有 4 个计数。所以所有具有高计数的值都应该在同一个数组中。

任何帮助都将受到高度评价!!!

我正在使用最新版本的 mongodb 4.0

标签: node.jsmongodbmongooseaggregation-framework

解决方案


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

$sort按计数对数据进行排序。

初始$group获取每个gift_id 的最大和最小文档元素,然后$group将最大和最小值文档推送到数组中。

db.colname.aggregate([
  {"$sort":{"count":-1}},
  {"$group":{"_id":"$_id.giftId","maxdoc":{"$first":"$$ROOT"}, "mindoc":{"$last":"$$ROOT"}}},
  {"$group":{"_id":null,"array1":{"$push":{"_id":"$maxdoc._id", "count":"$maxdoc.count"}}, "array2":{"$push":{"_id":"$mindoc._id", "count":"$mindoc.count"}}}},
  {"$project":{"_id":0}}
])

推荐阅读