【问题标题】:Populate JSON query result in MongoDB在 MongoDB 中填充 JSON 查询结果
【发布时间】:2021-06-27 05:23:03
【问题描述】:

我需要部分填充使用 MongoDB 完成的搜索结果。

搜索是基于MongoDB中保存的统计数据,但在范围内它可能有一天没有价值,需要用pair: missing date: zero来填充

以这个结果为例,2021-06-23 没有数据,所以我需要用 2021-06-23 填充。

在 MongoDB 上进行查找时,有什么方法可以直接填充?还是使用Javascript?

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

我使用 Java 脚本填充了数据。

此函数返回带有日期的数组

get__Dates__From__Interval = (startDate, stopDate) => {
    var dateArray = []
    var currentDate = moment(startDate)
    var stopDate = moment(stopDate)
    while (currentDate <= stopDate) {
        dateArray.push(moment(currentDate).format('YYYY-MM-DD'))
        currentDate = moment(currentDate).add(1, 'days')
    }

    return dateArray
}

使用日期数组我循环并推送待处理的日期

 let arrayDate = functions.get__Dates__From__Interval(startDate, endDate);

 var arrayDateLength = arrayDate.length;

   for (var i = 0; i < arrayDateLength; i++) {

      let index = response.findIndex(val => val.date == arrayDate[i]);
      if (index < 0) {
            response.push({ quantity: 0, date: arrayDate[i] });
      }
   }
            

这里我根据日期排序数组

sort__dates = (a, b) => {
    if (a.date < b.date)
        return -1;
    if (a.date > b.date)
        return 1;
    return 0;
}

response.sort(functions.sort__dates);

return res.status(200).send({ error: false, response });

【讨论】:

    猜你喜欢
    • 2021-09-19
    • 2016-03-06
    • 2013-11-03
    • 2021-03-03
    • 1970-01-01
    • 2014-01-05
    • 2017-12-24
    • 2021-02-16
    • 1970-01-01
    相关资源
    最近更新 更多