是否有可能检查mongo数据库是否已存在?
答案 0 :(得分:13)
是的,您可以获取现有数据库的列表。从Java驱动程序中,您可以执行类似这样的操作,以获取在localhost上运行的 mongod 服务器上的数据库名称
Mongo mongo = new Mongo( "127.0.0.1", 27017 );
List<String> databaseNames = mongo.getDatabaseNames();
这相当于mongo shell“show dbs”命令。我相信所有驱动程序中都存在类似的方法。
答案 1 :(得分:5)
从shell中,如果您想明确检查数据库是否存在:
db.getMongo().getDBNames().indexOf("mydb");
如果“mydb”不存在,将返回“-1”。
要从shell中使用它:
if [ $(mongo localhost:27017 --eval 'db.getMongo().getDBNames().indexOf("mydb")' --quiet) -lt 0 ]; then
echo "mydb does not exist"
else
echo "mydb exists"
fi
答案 2 :(得分:3)
对于因为方法server {
charset utf-8;
listen 80;
server_name example.com;
root /path;
include snippets/wordpress.conf;
auth_basic "=?UTF-8?Q?=D0=92=D0=B2=D0=B5=D0=B4=D0=B8=D1=82=D0=B5=20=D0=BF=D0=B0=D1=80=D0=BE=D0=BB=D1=8C.?=";
auth_basic_user_file /etc/nginx/.htpasswd;
}
被折旧/不可用而来到这里的任何人,以下是获取现有数据库列表的新方法:
getDatabaseNames();
这是一个验证数据库是否被找到的方法:
MongoClient mongoClient = new MongoClient();
MongoCursor<String> dbsCursor = mongoClient.listDatabaseNames().iterator();
while(dbsCursor.hasNext()) {
System.out.println(dbsCursor.next());
}
答案 3 :(得分:1)
在python中使用Pymongo
from pymongo import MongoClient
db_name = "foo"
conn = MongoClient('mongodb://localhost,localhost:27017')
db = self.conn[str(db_name)]
if bool(db_name in conn.database_names()):
collection.drop()
答案 4 :(得分:1)
我想添加一个C#版本。我正在使用MongoDB.Driver 2.2.2。
static bool DatabaseExists(string connectionString)
{
var mongoUri = new MongoUrl(connectionString);
var client = new MongoClient(mongoUri);
var dbList = Enumerate(client.ListDatabases()).Select(db => db.GetValue("name").AsString);
return dbList.Contains(mongoUri.DatabaseName);
}
static IEnumerable<BsonDocument> Enumerate(IAsyncCursor<BsonDocument> docs)
{
while (docs.MoveNext())
{
foreach (var item in docs.Current)
{
yield return item;
}
}
}
答案 5 :(得分:1)
使用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);
}
用法:
if (!DatabaseExists("FooDb")
{
// create and seed db
}
答案 6 :(得分:0)
试试这个,它对我有用(在Mac OSx上)
MongoClient mongoClient = new MongoClient("localhost");
/** **/
boolean dbExist =
mongoClient.listDatabaseNames().
into(new ArrayList<String>()).contains("TEST");
System.out.print(dbExist);
答案 7 :(得分:0)
上面的PyMongo示例对我没有用,所以我使用更标准的list_databases()方法将其重写为MongoClient库:
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
答案 8 :(得分:0)
就我而言,我无法使用listDatabaseNames
,因为我的用户无权调用此函数。相反,我只是假设它存在并在此数据库上调用一个方法,如果该方法不存在或缺少权限,该方法将失败。
演示C#代码:
/// <summary>
/// Tests the connection to the MongoDB server, and if the database already exists.
/// If not or an error is detected, an exception is thrown.
/// </summary>
public static void TestConnection(string mongoUrl, string mongoDatabase) {
var client = new MongoClient(mongoUrl);
var database = client.GetDatabase(mongoDatabase);
try {
// Try to perform an action on this database; will fail if it does not exist
database.ListCollections();
}
catch {
throw new Exception("Connection established, " +
"but database does not exist (or missing rights): " + mongoDatabase);
}
}