简体   繁体   English

mongodb + nodejs查找并返回文档中的特定字段

[英]mongodb + nodejs to find and return specific fields in documents

I'm trying to extract specific document fields from a mongodb collection (v 3.0.8 at MongoLab). 我正在尝试从mongodb集合 (MongoLab中的3.0.8版)中提取特定的文档字段 The returned documents must fall within a date range. 退回的文件必须在日期范围内。 My goal is to extract specific fields from these documents. 我的目标是从这些文档中提取特定字段。 My nodejs code, 我的nodejs代码,

var query = {}, operator1 = {}, operator2 = {}, operator3 = {} ;

operator1.$gte = +startDate;
operator2.$lte = +endDate;
operator3.$ne  = 'move';

query['xid'] = 1; // Problem here?
query['date']  = Object.assign(operator1, operator2);
query['type']  = operator3;

console.log(query);

MongoClient.connect(connection, function(err, db) {

    if(err){ 
        res.send(err); 
    } else {
        db.collection('jbone')
          .find(query)
          .toArray(function(err, result){
              console.log(err);
            res.json(result);
            });
    };
});

If I opt to return all fields in the date range, the query works fine. 如果我选择返回日期范围内的所有字段,则查询工作正常。 If I select only field xid I get no results. 如果仅选择字段xid不会获得任何结果。 My query object looks sensible according to the docs . 根据文档,我的query对象看起来很明智。 console.log(err) gives: console.log(err)提供:

    { xid: 1,
      date: { '$gte': 20160101, '$lte': 20160107 },
      type: { '$ne': 'move' } }
   null

null is the err . nullerr

Can anyone help me understand what I'm doing wrong? 谁能帮助我了解我在做什么错?

Or point me to another similar SO questions with an answer? 还是用答案将我指向另一个类似的问题?

Thanks 谢谢

To select the specific field could be done as below 要选择特定字段,可以按照以下步骤进行

.find( 
  {date: { '$gte': 20160101, '$lte': 20160107 }, type: { '$ne': 'move' }},
  { xid: 1} )

Sample codes as following. 示例代码如下。

   query['date']  = Object.assign(operator1, operator2);
   query['type']  = operator3;
    db.collection('jbone')
      .find(query, {xid: 1})
      .toArray(function(err, result){
          console.log(err);
        res.json(result);
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM