首页 > 解决方案 > 使用 Mongo shell 计算每个给定日期和文档列表的集合数

问题描述

我在 Mongo DB 中有以下集合:

我还有一个日期列表:

my_dates = [“2019 年 11 月 1 日”、“2019 年 11 月 3 日”、“2019 年 11 月 5 日”、“2020 年 1 月 1 日”]

我想要:

我堆积了能够计算以 AAA 或 BBB 开头的集合的文档数量,如下所示:

db.getCollectionNames().forEach(function(collection) 
{
  if(collection.startsWith("AAA") || collection.startsWith("BBB"))
  {
    resultCount = db[collection].count();
    print("Results count for " + collection + ":\t"+ resultCount);
    }
  });

可以像这样向集合名称添加日期:

if(collection.startsWith("AAA"+"-01-Oct-2019"))

但我不知道如何使用 my_dates 中的元素对其进行迭代。

标签: mongodb

解决方案


看看这个解决方案是否满足您的要求:

您可以使用方法或运算符迭代my_dates数组:.forEachfor

for(var i=0; i<my_dates.length; i++) {
    print(my_dates[i])
}

MongoDB 提供了exists检查是否创建集合的方法(可以是空集合):

var my_dates    = ["01-Nov-2019", "03-Nov-2019", "05-Nov-2019", "01-Jan-2020"];
my_dates.forEach(function(date){
    ["AAA", "BBB"].forEach(function(prefix){
        var col = prefix + "-" + date;
        //Check if exists
        if(db.getCollection(col).exists() !=null){
            print("Results count for " + col + ":\t"+ db.getCollection(col).count());    
        } else {
            //Not exists
            print("Results count for " + col + ":\t"+ "-1");
        }
    });
});

推荐阅读