MongoDB 是一个基于分布式文件存储的数据库。比较适合存放JSON数据。
下面是最简单的一段mongodb代码查找代码,先列出所有的数据库名称:listCollections,再列出某个数据集下的所有数据,如下:
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://user:passXXXXX:xxxcvxcvxcvxcv:29033/dbXXXXXvp";
const database = "xxxxxx"
MongoClient.connect(url, function(err, client) {
if (err) throw err;
console.log("数据库已创建!");
const allCollections = [];
client
.db(database)
.listCollections()
.toArray(function(err, collections) {
if(err) console.log(err);
console.log(allCollections)
client
.db(database)
.collection('systemLog')
.find()
.toArray((err, collections) => {
console.log(collections, collections.length)
client.close()
})
});
});
其实toArray等方法默认返回的是promise对象,上述代码则可简化为:
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://user:passXXXXX:xxxcvxcvxcvxcv:29033/dbXXXXXvp";
const database = "xxxxxx"
const client = new MongoClient(url, options);
(async() => {
await client.connect();
const db = client.db(database);
const collections = await db.listCollections().toArray();
console.log(collections.map(collection => collection.name));
const systemAuditLogs = await db.collection('systemLogs').find().toArray()
console.log(systemAuditLogs);
// client.close()
})();
上述代码还需要添加相应的try/catch异常处理代码,这里略
回复 (0)
微信扫码 立即评论