【问题标题】:MongoDb: Accessing Collection and console log ObjectMongoDb:访问集合和控制台日志对象
【发布时间】:2020-11-03 05:05:57
【问题描述】:

我正在尝试访问一个 MongoDB 集合,并且我想从这个集合中控制台记录一个对象。

我按如下方式连接到我的 MongoDB:

async function main(){
  /**
   * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
   * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
   */
  const uri = process.env.DB_Port;
  const client = new MongoClient(uri,{ useNewUrlParser: true, useUnifiedTopology: true});

  try {
      // Connect to the MongoDB cluster
      await client.connect();

      // Make the appropriate DB calls
      await  listDatabases(client);

  } catch (e) {
      console.error(e);
  } finally {
      await client.close();
  }
  
}

main().catch(console.error);

async function listDatabases(client){
  databasesList = await client.db().admin().listDatabases();

  console.log("Databases:");
  databasesList.databases.forEach(db => console.log(` - ${db.name}`));
};

此控制台记录:

Databases:
 - radiototem
 - test
 - admin
 - local

现在我想访问集合测试并控制台记录其中的所有内容。我怎样才能做到这一点?

最好的问候

【问题讨论】:

  • well test 是一个数据库而不是一个集合。您是否尝试过db.listCollections() 应该显示该特定数据库中的所有集合。
  • 对了。但是如何访问特定的数据库并 conaole 记录所有条目?

标签: node.js mongodb express


【解决方案1】:

为了从 MongoDB 中获取项目,您首先需要访问存储它们的集合。 MongoDB 中的集合与 SQL 中的表基本相同。

要获取集合,请在您从 client.db() 获取的 DB 对象上调用 .collection() 函数,并使用您的集合名称,如下所示:

client.db().collection('test');    // This gives you the collection "test"

如果要从集合中获取项目,可以使用.find() 方法。您可以向它传递一个查询参数,该参数是您定义的对象,应根据其属性选择哪些项目。

例如,从 users 集合中获取所有名为 peter 的用户:

const db = client.db();
const users = db.collection('users');
const usersNamedPeterCursor = users.find({ name: 'Peter' });

现在,如果您想从集合中获取所有项目,您可以简单地使用不带查询参数的 find 方法。这将返回集合中的所有项目。

find 方法返回一个Cursor 对象,它允许您与返回的数据进行交互。您可以在 Cursor 对象上调用方法,例如 max()min()toArray()each() 等等。

因此,如果您想控制台记录您收藏中的每个项目,您可以这样做:

client.db().collection('test').find().each(function(error, item) {
 // console .log your item or do something else with it
});

【讨论】:

  • 您的回答帮助我了解了如何使用 MongoDB。非常感谢!
猜你喜欢
  • 2016-02-17
  • 2019-10-06
  • 1970-01-01
  • 2020-10-08
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
  • 2013-05-06
相关资源
最近更新 更多