如何使用mongodb(node.js)将集合内的所有值组成数组

时间:2018-10-06 07:40:57

标签: javascript node.js mongodb

我一直在等待诺言。

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, { useNewUrlParser: true } , function(err, db) {
    if (err) throw err;

    var dbo = db.db("mydb");
    var gr = dbo.collection("collectionname").distinct("name");

    // var everyrecord = dbo.collection("collectionname").find({}).toArray();

    console.log(gr);

    db.close();
});

3 个答案:

答案 0 :(得分:1)

如果使函数 async ,则只需 await 结果:

MongoClient.connect(url, { useNewUrlParser: true } , async function(err, db) {
    // ...

    var gr = await dbo.collection("collectionname").distinct("name");
    console.log(gr);

    // ...
});

答案 1 :(得分:0)

您可以使用.toArray()实现此目标

    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/mydb";

    MongoClient.connect(url, { useNewUrlParser: true } , function(err, db) {

      if (err) throw err;

      db.collection("collectionname").distinct("name").toArray(function (error, response) {
         console.log(error);
         console.log(response);
      });
    });

答案 2 :(得分:0)

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, { useNewUrlParser: true } , function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

 var gr = dbo.collection("collectionname").distinct("name");
 gr = gr.toArray();

// var everyrecord = dbo.collection("collectionname").find({}).toArray();

  console.log(gr);

  db.close();
});