Select from collection that I know only suffix collection's name

I need a query that finds from collection- that I dont have the collection’s name
I know the collection’s suffix name
the collection name is something like 123456Aggregation
but the number is random
so I need to read from the collection with name " .*Aggregation"
i found that I could use something like this
FROM sys.tables agg WHERE like ‘%Aggregation’
.tables are all collections and is the collection’s name
but it doesn’t work
thank you

Hello @kineret_ao ,

Welcome to The MongoDB Community Forums! :wave:

Please correct me if my understanding of your use-case is not correct. You are trying to query a collection but the exact collection name is not known instead only the last part of collection name is known, is my understanding correct?

If not, then please share more details regarding your use case such as:

  • MongoDB Version
  • What are you trying to do and why? What is the end result you expect from this?
  • What have you tried till now to achieve this goal?

If my understand is correct then you can try some thing as follows:

You can divide your question in two parts:

  1. How to get collection name with collection name’s ending/suffix?
    db.getCollectionNames().filter(name => name.endsWith("Aggregation"))
    Above Javascript operation in the mongosh shell will give you all the collection names ending with “Aggregation”. Now you go through the results and can query the database accordingly.

  2. Using the output of the previous step, you can execute some operations on the database. For example if you put the name of the desired collection into a variable collName , you may be able to do something like db[collName].find(...) or db[collName].aggregate(...) in the mongosh shell. To learn more about how to connect and query from MongoDB Database, I would recommend you to go through

Note: Please test the query as per your requirements and make changes accordingly.


This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.