0

I have following collections in 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

I also have a list of dates:

my_dates = ["01-Nov-2019", "03-Nov-2019", "05-Nov-2019", "01-Jan-2020"]

I want to:

  • count number of documents in collections AAA and BBB only for dates in my_dates

  • be notified if date from my_dates does not have collection AAA or BBB (can be just count = 0 or text that particular collection do not exists).

  • count number of AAA's and BBB's to clearly see that it is equal to len(my_dates) (because len(my_dates) can be over 100).

I stacked with be able to count number of documents for collections that starts with AAA or BBB like this:

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

Adding date to collection name can be done like this:

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

but I do not know how to iterate it with elements from my_dates.

1 Answer 1

0

Take a look if this solution meets your requirements:

You may iterate my_dates array with .forEach method or with for operator:

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

MongoDB provides method exists which checks if collection is created (can be empty collection):

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");
        }
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Second solution hangs in my intellishell.
@Piotrek It hangs probably because .count() takes too much time. Try to modfy the script and not count total values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.