正在更改 mongo 数据库

Changing mongo database

我想使用节点的本机 2.0 mongodb 驱动程序在我的副本集中查询一个集合。我可以连接 admin 数据库并对其进行身份验证,但如何切换数据库以查询我感兴趣的集合?

var mongodb  = require('mongodb');
var MongoClient = mongodb.MongoClient;

var url = "mongodb://user:pass@db1,db2,db3/admin";

MongoClient.connect(url, function(err, db) {

    console.log("Connected correctly to server");
    console.log("Current database", db.databaseName);

    // switch context to database foo
    // foo.bar.findOne();

    db.close();

});

来自 MongoDB 2.0.0 驱动程序 docs

Indirectly Against Another Database

In some cases you might have to authenticate against another database than the one you intend to connect to. This is referred to as delegated authentication. Say you wish to connect to the foo database but the user is defined in the admin database. Let’s look at how we would accomplish this.

var mongodb  = require('mongodb');
var MongoClient = mongodb.MongoClient;

var url = "mongodb://user:pass@db1,db2,db3/foo?authSource=admin";

MongoClient.connect(url, function(err, db) {

    console.log("Connected correctly to server");
    console.log("Current database", db.databaseName);

    //db==foo

    db.close();

});