簡體   English   中英

如何獲取今天用mongoose創建的文檔數量?

[英]how to get number of documents which is created today with mongoose?

如何獲取今天用mongoose創建的文檔數量? 我正在使用MEAN堆棧。 我讀了Mongoose Api Docs,但是什么都不懂:/

默認情況下沒有辦法。

除非您將文檔明確存儲在MongoDB中,否則文檔沒有與之關聯的創建日期。

換句話說,您的Mongoose架構應該具有類似已created字段的內容:

const blogSchema = new Schema({
  created: {type: Date, default: Date.now}
});

然后搜索匹配的文檔:

const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
doc.find({created: {$gte: today}}).exec(callback);

假設您在架構中創建了日期字段createdAt並希望獲得今天注冊的用戶數,則應創建兩個日期對象實例,以用於日期范圍查詢, startend日期。

您的start日期對象應將當前日期時間小時保持在00:00:00.000 (毫秒精度),並將今天日期的小時數設置為23:59:59.999end日期變量:

var start = new Date();
start.setHours(0,0,0,0);

var end = new Date();
end.setHours(23,59,59,999);

然后像往常一樣在$match運算符中的MongoDB聚合管道中傳遞修改后的日期對象:

var pipeline = [
    {
        "$match": {
            "createdAt": { "$gte": start, "$lt": end }
        }
    },
    {
        "$group": {
            "_id": null,
            "count": { "$sum": 1 }
        }
    }
];

Model.aggregate(pipeline, function (err, result){
    if (err) throw new Error();
    console.log(JSON.stringify(result));
});

如果您正在使用momentjs庫,可以通過在當前日期對象上使用startOf()endOf()方法來完成此操作,並將字符串'day'作為參數傳遞:

var start = moment().startOf('day'); // set to 12:00 am today
var end = moment().endOf('day'); // set to 23:59 pm today

暫無
暫無

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

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