mongodb - 使用 Mongo shell 计算每个给定日期和文档列表的集合数
问题描述
我在 Mongo DB 中有以下集合:
- AAA-01-Nov-2019
- AAA-02-Nov-2019
- AAA-03-Nov-2019
- AAA-04-Nov-2019
- AAA-05-Nov-2019
- AAA-06-Nov-2019
- AAA-07-Nov-2019
- AAA-08-Nov-2019
- AAA-09-Nov-2019
- BBB-01-Nov-2019
- BBB-02-Nov-2019
- BBB-03-Nov-2019
- BBB-04-Nov-2019
- BBB-05-Nov-2019
- BBB-06-Nov-2019
- BBB-07-Nov-2019
- BBB-08-Nov-2019
- BBB-09-Nov-2019
我还有一个日期列表:
my_dates = [“2019 年 11 月 1 日”、“2019 年 11 月 3 日”、“2019 年 11 月 5 日”、“2020 年 1 月 1 日”]
我想要:
仅针对 my_dates 中的日期计算 AAA 和 BBB 集合中的文档数
如果来自 my_dates 的日期没有集合 AAA 或 BBB(可以只是 count = 0 或特定集合不存在的文本),则会收到通知。
计算 AAA 和 BBB 的数量以清楚地看到它等于 len(my_dates)(因为 len(my_dates) 可以超过 100)。
我堆积了能够计算以 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 中的元素对其进行迭代。
解决方案
看看这个解决方案是否满足您的要求:
您可以使用方法或运算符迭代my_dates
数组:.forEach
for
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");
}
});
});
推荐阅读
- git - 致命:不是 git 存储库(或任何父目录):.git on rake task on Heroku
- python - Python Pandas 处理 308 请求
- regex - 仅从字符串中提取捕获组
- python - 课堂上直接打印——python
- r - 从 dplyr 数据返回中总结
- pandas - Pandas.dropna 方法不能删除 Nan 值行(或列)
- laravel - Laravel Eloquent 条件不起作用的地方
- json - jq将键数组与值数组合并
- python - 过滤二维数组/列表并替换python中的值
- javascript - Javascript循环和对象创建