简体   繁体   中英

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). The returned documents must fall within a date range. My goal is to extract specific fields from these documents. My nodejs code,

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. My query object looks sensible according to the docs . console.log(err) gives:

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

null is the err .

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);
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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