[英]Fetch all documents of a database in MongoDB using nodejs
Iam是MongoDB和nodejs的新手。 我有一個要求,我需要根據此要求提取mongo數據庫中的所有文檔。 我發現了許多代碼,這些代碼使我可以從數據庫中的集合中獲取所有文檔,但是沒有代碼可以一次性獲取數據庫中的所有文檔。 游標可以用於此嗎? 以下是我發現的代碼:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:port/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("customers").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
我想獲取“ mydb”下的所有文檔,而不僅僅是“集合”下的文檔。 最終輸出應該是其中包含文檔JSON的JSON。
注意:“ mydb”的多個集合下的所有文檔均采用相同的json格式。
您必須分別查詢每個collection
並將它們連接在一起,您如何看待這樣的事情:
var dataFromAllCollections = [];
const collections = db.getCollectionNames();
for(var i = 0; i< collections.length; i++){
dataFromAllCollections.concat(db.getCollection(collections[i]).find());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.