Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Loop through all MongoDB collections and execute query?
To loop through all MongoDB collections and execute a query, use db.getCollectionNames() to retrieve collection names, then iterate using forEach() to perform operations on each collection.
Syntax
db.getCollectionNames().forEach(function(collectionName) {
// Execute your query on each collection
var result = db[collectionName].find(query);
// Process the result
});
Example: Get Latest Document from Each Collection
Loop through all collections and get the timestamp of the most recent document ?
db.getCollectionNames().forEach(function(collectionName) {
var latest = db[collectionName].find().sort({_id:-1}).limit(1);
if (latest.hasNext()) {
printjson(latest.next()._id.getTimestamp());
}
});
The output shows the creation timestamp of the latest document from each collection ?
ISODate("2019-02-21T18:52:43Z")
ISODate("2019-03-19T17:49:00Z")
ISODate("2019-03-06T15:40:12Z")
ISODate("2019-03-15T16:31:50Z")
ISODate("2019-02-21T15:40:52Z")
ISODate("2019-03-06T06:14:37Z")
ISODate("2019-02-21T19:29:15Z")
ISODate("2019-03-15T13:35:33Z")
ISODate("2019-03-14T21:13:58Z")
ISODate("2019-03-18T22:02:54Z")
ISODate("2019-03-22T18:01:45Z")
ISODate("2019-03-06T16:21:14Z")
How It Works
-
db.getCollectionNames()returns an array of all collection names in the database -
forEach()iterates through each collection name -
db[collectionName]dynamically accesses each collection -
sort({_id:-1}).limit(1)gets the most recent document by ObjectId -
hasNext()checks if the collection has documents before processing
Conclusion
Use db.getCollectionNames().forEach() to iterate through all collections and execute queries dynamically. This approach is useful for database maintenance tasks and cross-collection operations.
Advertisements
