2016-04-03 76 views
-3

MongoDB中的检索数据的价值,我有以下结构:如何蒙戈集合

{ 
"_id" : "123", 
    "username" : "[email protected]", 
} 

我想检索值“[email protected]”我怎么做一个集合的学生?

不使用db.getCollection('students').find({username:"[email protected]"})

+0

你用什么语言查询mongoDB? – JordanHendrix

+1

你试过了吗? – Saleem

+0

是的,我试过。我正在使用JavaScript。我甚至尝试使用robomongo控制台(mongoshell)来检索值,但无法执行此操作。所以我想在不使用db.getCollection('students')的情况下获取[email protected] find({username:“[email protected]”})因为我想要集合中存在的所有这些字段的列表 – ssstudent

回答

0

根据您在您的评论所提供的附加信息[email protected]明确地发现,要检索所有学生的用户名您的收藏。这里是这样做的代码:假设你有两个学生的集合中的输出可能看起来像这样

var mongo = require('mongodb'); 
var url = 'mongodb://localhost:27017/test'; 

mongo.connect(url, function(e, db) { 
    if (e) return console.error(e); 
    db.collection('students').find().project({_id: 0, username: 1}).forEach(function(doc) { 
     console.log(doc.username); 
    }, function(e){ 
     if(e) console.error(e); 
     db.close(); 
    }); 
}); 

[email protected] 
[email protected] 

如果你想在一个阵列的用户名,使用指定者而不是forEach(查看使用信息的MongoDB API文档:http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#toArray