MongoDb以数组形式仅返回特定字段(电话号码)

MongoDb以数组形式仅返回特定字段(电话号码),mongodb,mongoose,mongodb-query,Mongodb,Mongoose,Mongodb Query,我想以数组的形式从我的一个模式中查询并获取所有电话号码 我的模式是 var doctorSchema = new Schema({ profile: { fullname: String, gender: String, email: String, dob: Date, contact: { mobile: String }, } }); 有人能帮

我想以数组的形式从我的一个模式中查询并获取所有电话号码

我的模式是

 var doctorSchema = new Schema({
      profile: {
        fullname: String,
        gender: String,
        email: String,
        dob: Date,
        contact: 
        { mobile: String },
        } 
        });
有人能帮我吗?我如何只查询contact.mobile并将所有号码存储在一个数组中

我尝试了$map,但它不起作用。

对于这些样本数据

{ "_id" : ObjectId("56bef5f4d43b2f3239759505"), "profile" : { "fullname" : "DJ", "email" : "hhh.com", "contact" : { "mobile" : "123456" } } }
{ "_id" : ObjectId("56bef605d43b2f3239759506"), "profile" : { "fullname" : "ad", "email" : "gg.com", "contact" : { "mobile" : "127886" } } }
结果是

[ "123456", "127886" ]
您可以使用点符号在模型上调用方法来指定嵌入的文档字段。这将查询单个集合中指定字段的所有不同值,并以数组形式返回结果:

var callback = function (err, result) {
    if (err) { /* handle err */ };
    console.log('unique mobile numbers', result);
};

Doctor.distinct("profile.contact.mobile", callback);
var promise = Doctor.find({ }).select("profile.contact.mobile").exec();
promise.then(function (results) {
    var numbers = results.map(function (m) {
        return m.profile.contact.mobile;
    });
    console.log(numbers);
}).then(null, function (err) {
    console.log(err);
});

在mongo shell中,这相当于:

var mobilenumbers = db.doctors.distinct("profile.contact.mobile");
您还可以使用查询返回的上的方法,作为在数组中获取结果的另一种方法:

var callback = function (err, result) {
    if (err) { /* handle err */ };
    console.log('unique mobile numbers', result);
};

Doctor.distinct("profile.contact.mobile", callback);
var promise = Doctor.find({ }).select("profile.contact.mobile").exec();
promise.then(function (results) {
    var numbers = results.map(function (m) {
        return m.profile.contact.mobile;
    });
    console.log(numbers);
}).then(null, function (err) {
    console.log(err);
});
mongo shell等效操作使用游标方法,如下所示:

var mobilenumbers = db.doctors.find({}, {"profile.contact.mobile": 1})
                              .map(function (m){ 
                                   return m.profile.contact.mobile; 
                              });
Doctor.find({},'contact.mobile'…)
应该返回您想要的内容。