[英]Show results mongodb nodejs
i need show result in my database mongodb.我需要在我的数据库 mongodb 中显示结果。
Im use mongodb.cloud atlas i already created database now i need show result in my database我使用 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();
});
Im expected result in sample_restaurants.restaurants in console.log我在 console.log 中的 sample_restaurants.restaurants 的预期结果
EDIT编辑
Im use your answer but my problème return error我使用你的答案,但我的问题返回错误
MongoError: no primary server available
this code这段代码
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)
});
});
First improve your code to fix the error:首先改进您的代码以修复错误:
let db = await MongoClient.connect(MONGO_URI, { useNewUrlParser: true }); db = await db.db(); const collection = db.collection('sample_restaurants');
You have two different ways to get the data.您有两种不同的方式来获取数据。
1- If your results are not a lot, you can get all of them in once and then print them. 1- 如果您的结果不是很多,您可以一次获得所有结果,然后打印出来。
const results = await collection.find({}).toArray(); console.log(results)
2- If the number of the records is something like 2 million records, you can not use it this way. 2- 如果记录数是 200 万条记录,则不能这样使用。 Have to create a cursor and then get them one by one.
必须创建一个 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.