如何根据MongoDB中的日期制作存储桶?

时间:2017-10-04 18:31:38

标签: mongodb mongodb-query

我的数据看起来像这样 -

val lessNoisyNeighbors = noisyNeighbors.map { neighbor =>
  neighbor.copy(pets = neighbor.pets.filter(_ != petTypeToRemove))
}

我试图得到像这样的结果 -

{
   'field1' : 123
   "timestamp" : ISODate("2017-10-04T13:35:57.621Z")
},
{
   'field1' : 123
   "timestamp" : ISODate("2017-10-04T13:35:57.621Z")
},
{
   'field1' : 123
   "timestamp" : ISODate("2012-10-04T13:35:57.621Z")
},
{
   'field1' : 123
   "timestamp" : ISODate("2012-10-04T13:35:57.621Z")
},
{
   'field1' : 123
   "timestamp" : ISODate("2012-10-04T13:35:57.621Z")
}

现在我的查询是 -

{ "date" : '2012-10-04', "count" : 3 },
{ "date" : '2017-10-04', "count" : 2 }

它汇总了恰到好处的日期,但没有显示日期。

1 个答案:

答案 0 :(得分:2)

使用您的数据,这个agg表达式:

db.foo.aggregate([
  {$group: {_id:"$timestamp", n:{$sum:1}}}
  ,{$addFields: {datestr: {$dateToString: {format: "%Y-%m-%d", date: "$_id"}}}}

              ]);

产量

{
    "_id" : ISODate("2012-10-04T13:35:57.621Z"),
    "n" : 3,
    "datestr" : "2012-10-04"
}
{
  "_id" : ISODate("2017-10-04T13:35:57.621Z"),
  "n" : 2,
  "datestr" : "2017-10-04"
}

如果你想在Y-m-d部分进行攻击,请改为对其进行分组:

db.foo.aggregate([
{$addFields: {datestr: {$dateToString: {format: "%Y-%m-%d", date: "$timestamp"}}}}
,{$group: {_id:"$datestr", n:{$sum:1}}}

              ]);