0

Using ObjcMongodb framework- How to find all the collections in a db similar to show collections (shell command)

Debasis Das
  • 102
  • 7

2 Answers2

0

You can invoke arbitrary database commands using these methods on MongoConnection:

- (NSDictionary *) runCommandWithName:(NSString *) commandName
                       onDatabaseName:(NSString *) databaseName
                                error:(NSError * __autoreleasing *) error;
- (NSDictionary *) runCommandWithDictionary:(NSDictionary *) dictionary
                             onDatabaseName:(NSString *) databaseName
                                      error:(NSError * __autoreleasing *) error;

See this answer for an example.

Community
  • 1
  • 1
paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
0

To list all collections in a database, query the system.namespaces collection.

The system.namespaces collection includes both collection names and indexes so you need to filter the results to ignore any system collections (eg: system.indexes) as well as those containing $ (indexes/special collections).

Example code:

NSError *error = nil;
MongoConnection *dbConn = [MongoConnection connectionForServer:@"127.0.0.1" error:&error];

// For database "mydb", look in "system.namespaces" collection
MongoDBCollection *collection = [dbConn collectionWithName:@"mydb.system.namespaces"];

NSArray *results = [collection findAllWithError:&error];
for (BSONDocument *result in results) {
    NSDictionary *systemNamespace = [BSONDecoder decodeDictionaryWithDocument:result];
    NSString *collName = [systemNamespace objectForKey:@"name"];

    // Namespaces to ignore: mydb.system.* (system) and those containing $ (indexes/special)
    if (
        ([collName rangeOfString:@".system."].location == NSNotFound) &&
        ([collName rangeOfString:@"$"].location == NSNotFound)) {
        NSLog(@"Found collection: %@", collName);
    } else {
        // NSLog(@"Ignoring: %@", collName);
    }
}
Stennie
  • 63,885
  • 14
  • 149
  • 175