Check if mongodb database exists?

前端 未结 9 1479
孤街浪徒
孤街浪徒 2020-12-14 21:58

Is there a possibility to check if a mongo database allready exists?

相关标签:
9条回答
  • 2020-12-14 22:47

    Yes, you can get the list of existing databases. From the Java driver you could do something like this to get the database names on a mongod server running on localhost

    Mongo mongo = new Mongo( "127.0.0.1", 27017 );
    List<String> databaseNames = mongo.getDatabaseNames();
    

    This is equivalent to the mongo shell "show dbs" command. I am sure similar methods exist in all of the drivers.

    0 讨论(0)
  • 2020-12-14 22:48

    using MongoDb c# Driver 2.4

        private bool DatabaseExists(string database)
        {
           // _client is IMongoClient
            var dbList = _client.ListDatabases().ToList().Select(db => db.GetValue("name").AsString);
            return dbList.Contains(database);
        }
    

    usage:

            if (!DatabaseExists("FooDb")
            {
                // create and seed db
    
            }
    
    0 讨论(0)
  • 2020-12-14 22:51

    The PyMongo example above didn't work for me, so I rewrote it using the more standard list_databases() method to the MongoClient library:

    from pymongo import MongoClient db_name = "foo" conn = MongoClient('mongodb://localhost,localhost:27017') if bool(db_name in conn.list_databases()): print true # or return true here else: print false # or return false here

    0 讨论(0)
提交回复
热议问题