簡體   English   中英

顯示結果 mongodb nodejs

[英]Show results mongodb nodejs

我需要在我的數據庫 mongodb 中顯示結果。

我使用 mongodb.cloud atlas 我已經創建了數據庫現在我需要在我的數據庫中顯示結果

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://test:test@cluster0.bvhvj.mongodb.net/*****? 
retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("sample_restaurants");
  // perform actions on the collection object
  // need show result database in console.log

client.close();
});

我在 console.log 中的 sample_restaurants.restaurants 的預期結果

編輯

我使用你的答案,但我的問題返回錯誤

MongoError: no primary server available

這段代碼

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://test:test@cluster0.bvhvj.mongodb.net/****? 
retryWrites=true&w=majority";
client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
   const collection = client.db("sample_restaurants").
   collection("restaurants").find({}).toArray(function(err,result)
   {
       if(err) throw err;
       console.log(result)
   });
});
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://test:test@cluster0.bvhvj.mongodb.net/*****? 
             retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {    
const collection = client.db("sample_restaurants").                   
               collection("restaurants").find({}).toArray(function(err,result)                                                           
         {
           if(err) throw err;
           console.log(result)
         });
});

首先改進您的代碼以修復錯誤:

 let db = await MongoClient.connect(MONGO_URI, { useNewUrlParser: true }); db = await db.db(); const collection = db.collection('sample_restaurants');

您有兩種不同的方式來獲取數據。

1- 如果您的結果不是很多,您可以一次獲得所有結果,然后打印出來。

 const results = await collection.find({}).toArray(); console.log(results)

2- 如果記錄數是 200 萬條記錄,則不能這樣使用。 必須創建一個 cursor 然后一個一個拿到。

 const cursor = collection.find(); while(await cursor.hasNext()) { const record = await cursor.next(); console.log(record); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM