[英]How to retrieve value of data in the mongo collection
在mongodb中,我有一個具有以下結構的集合學生
{
"_id" : "123",
"username" : "user@gmail.com",
}
我想檢索值 'user@gmail.com' 我該怎么做?
沒有使用db.getCollection('students').find({username:"hellouser@gmail.com"})
明確查找 user@gmail.com
根據您在評論中提供的附加信息,您希望檢索您收藏中所有學生的用戶名。 這是這樣做的代碼:
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();
});
});
假設您的集合中有兩個學生,輸出可能如下所示:
user@gmail.com
user1@gmail.com
如果您想在數組中使用用戶名,請使用 toArray 而不是 forEach(查看 MongoDB api 文檔以獲取使用信息: http : //mongodb.github.io/node-mongodb-native/2.1/api/Cursor .html#toArray )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.