在mongodb中获取types的数组

有没有解决这个问题的方法?

假设我有db作为;

{ name: "Alex" id: 1 } { name: "Felix" id: 2 } db.collection.find({}, {name:1, id:0}).toArray() 

回报为;

 result object name: Alex object name: Felix 

我已经限制了字段只能获得一个数组的名字。 有没有办法做到这一点? 为什么这个查询以[object OBJECT]格式返回?

我的解决scheme是; 遍历result并将每个名称对象插入到某个数组中。 我正在寻找与此不同的东西。 也许是关于我写的查询?

你是否将函数传递给toArray()

 var mongo = require('mongodb').MongoClient; var mongoURL = 'mongodb://localhost:27017/example'; mongo.connect(mongoURL, function(err,db){ db.collection('collection').find({}).toArray(function(err, res){ console.log(res); db.close(); }); }); 

用你的数据运行上面的代码将会返回所有存储的文件:

 C:\Users\james.bubb\node\>node test.js [ { _id: 571798647849a3c217e84d61, name: 'Alex', id: 1 }, { _id: 571798757849a3c217e84d62, name: 'Felix', id: 2 } ] 

或者,只显示名称而不是将整个结果logging到控制台(或任何您需要执行的操作):

 res.forEach(function(doc){ console.log(doc.name) }); 

doc是您存储的每个单独文档。

当然,您可以指定条件来在find()函数中过滤结果。

有一个很好的介绍在NPM站点上使用MongoDB和Node over(请参阅这里了解有关select文档的详细信息)。

据我所知你需要获得所有名称作为一个数组,所以在这种情况下,你可以使用聚合 :

 db.collection.aggregate([ {$group : {'_id' : "names", 'names' : {$push : '$name'}}} ]); 

结果你会得到这个:

 { "_id" : "names", "names" : [ "Alex", "Felix" ] } 

然后,您可以简单地从查询结果中获取所有用户名作为数组