使用ObjcMongodb框架-如何查找数据库中的所有集合,类似于显示集合(shell命令)
发布于 2014-07-28 01:21:32
您可以在MongoConnection上使用以下方法调用任意数据库命令:
- (NSDictionary *) runCommandWithName:(NSString *) commandName
onDatabaseName:(NSString *) databaseName
error:(NSError * __autoreleasing *) error;
- (NSDictionary *) runCommandWithDictionary:(NSDictionary *) dictionary
onDatabaseName:(NSString *) databaseName
error:(NSError * __autoreleasing *) error;有关示例,请参阅this answer。
发布于 2014-08-04 22:50:53
若要列出数据库中的所有集合,请查询system.namespaces集合。
system.namespaces集合包括集合名称和索引,因此您需要过滤结果以忽略任何系统集合(例如:system.indexes)以及那些包含$的集合(索引/特殊集合)。
示例代码:
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);
}
}https://stackoverflow.com/questions/24923056
复制相似问题