gpt4 book ai didi

node.js - mongodb中的聚合函数

转载 作者:可可西里 更新时间:2023-11-01 09:09:15 27 4
gpt4 key购买 nike

我有一个数据库数据如下

{
"_id" : ObjectId("5a2109572222085be93ef10d"),
"name" : "data1",
"date" : "2017-12-01T00:00.0Z",
"status" : "COMPLETED"},{
"_id" : ObjectId("5a2109572222085be93ef10d"),
"name" : "data1",
"date" : "2017-12-01T00:00.0Z",
"status" : "FAILED"}

我想要一个聚合输出如下

{ date:"2017-12-01T00:00:0Z", total:"2", completed:1, failed:1 }

我试过这段代码,但没有产生如上的结果

db.test.aggregate([
{$group: {_id : {date : '$date',status:'$status'}, total:{$sum :1}}},
{$project : {date : '$_id.date', status : '$_id.status', total : '$total', _id : 0}}
])

最佳答案

db.test.aggregate(

// Pipeline
[
// Stage 1
{
$group: {
_id:"$date",
total:{$sum:1},
failed:{$sum:{$cond:[{$eq:["$status","FAILED"]},1,0]}},
completed:{$sum:{$cond:[{$eq:["$status","COMPLETED"]},1,0]}}
}
},

// Stage 2
{
$project: {
date : '$_id',
total : 1,
failed : 1,
completed : 1,
_id : 0,
}
},

]
);

关于node.js - mongodb中的聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47588990/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com