簡體   English   中英

在MongoDB中按日期計數的記錄具有自定義日期范圍?

[英]Count of records by Date with custom date range in mongoDB?

我想按日期傳遞所有數據,同時按降序傳遞自定義日期范圍。 這是我的代碼

  var start = new Date(req.body.from_date);  // 2018-12-03
  start.setHours(0,0,0,0);

  var end = new Date(req.body.to_date);  // 2018-12-03
  end.setHours(23,59,59,999);

db.companies.aggregate([{
  $match: {
   $and : [
    {startDate: {$gte:start} }, 
    {endDate: {$lte:end} }
   ]
  },
 },
 {
  $group:{
    _id:{ startDate:"$startDate",endDate:"$endDate",
       day: { $dayOfMonth: "$entry_date" },
       month: { $month: "$entry_date" }, 
       year: { $year: "$entry_date" }
     }, 
     count: { $sum:1 },
     date: { $first: "$entry_date" }
   }
 },
 {
    $sort:{ entry_date: -1 }
 }
 {
  $project:{
   date:{
    $dateToString: { format: "%Y-%m-%d", date: "$date" }
   },
   count: 1,
   _id: 0
  }
 }])

如果我沒有通過$ match條件,它將顯示帶有日期的數據計數,但是當我嘗試通過並使其條件不起作用時。 任何想法 ?

提前致謝

日期包裝在MongoDb內置的ISODate()幫助器函數中,是一種方便的方式以可視方式將日期表示為字符串,同時仍然允許充分使用日期查詢和索引。

嘗試這個:

$and : [
    {startDate: {$gte: ISODate("2018-11-10T18:30:00.000Z")} }, 
    {endDate: {$lte: ISODate("2018-11-30T18:29:59.999Z")} }
   ]

我修復了它,$ project需要在$ match條件下需要我們的所有字段,就像我想要日期范圍的結果一樣,我的字段是entry_date

這是我的代碼...

  var company_id= company._id 
  var start = new Date(req.body.from_date);
  start.setHours(0,0,0,0);
  var end = new Date(req.body.to_date);
  end.setHours(23,59,59,999);

VisitorCompany.aggregate(
      [   
        {
          $match: {
            $and:[
              { entry_date: { $gt: start, $lt: end } },{company_id:""+company_id+""}
            ]
          }
        },
        { $sort : { entry_date : -1 } },
          {
              $group:
              {
                  _id:
                  {
                      day: { $dayOfMonth: "$entry_date" },
                      month: { $month: "$entry_date" }, 
                      year: { $year: "$entry_date" }
                  }, 
                  count: { $sum:1 },
                  entry_date: { $first: "$entry_date" }
              }
          },
          {
              $project:
              {
                  entry_date:
                  {
                      $dateToString: { format: "%Y-%m-%d", date: "$entry_date" }
                  },
                  count: 1,
                  _id: 0
              }
          }
      ])

輸出在這里...

    {
        "count": 1,
        "entry_date": "2018-11-18"
    },
    {
        "count": 2,
        "entry_date": "2018-11-22"
    },
    {
        "count": 2,
        "entry_date": "2018-11-23"
    },

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM