node.js - 在分组键上创建具有最少和最多计数的文档数组
问题描述
我有以下收藏
[
{
_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
解决方案
您可以使用以下聚合查询。
$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}}
])
推荐阅读
- javascript - 临时更改输入框样式
- node.js - 如何更新现有无服务器项目中的节点版本
- python - 根据条件将类名打印到字典 - BS4
- django - Django在验证后保留数据
- c# - 肥皂客户端返回不能破坏响应体 netcore
- r - 在r中的函数内使用assign时是否可以保留数据类型?
- ruby-on-rails - 创建 Ruby On Rails 应用程序时出现 Webpacker 错误
- python - WinError 6 - 句柄对可执行文件无效,但代码在调试模式下工作
- django - 类型数据的对象不是 Django 中的 JSON 可序列化错误
- kubernetes - Kubernetes 集群合并以最小化集群