Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I cannot filter out _id from results?

MongoDB database has following type of data:

{ _id: 5a4c5ffaeb092f0c1daac8b4, name: 'Jenny', age: 10 }

The code below prints out the _id too.

var url = 'mongodb://localhost:27017/learnyoumongo';
var mongo = require('mongodb').MongoClient;
mongo.connect(url, function(err, db) {
  if (err) throw err;
  // db gives access to the database
  const myDb = db.db('learnyoumongo');
  var parrots = myDb.collection('parrots');
  parrots.find({
    age: {
      $gt: parseInt(process.argv[2])
    }
  }, {
    name: 1,
    age: 1,
    _id: 0

  }).toArray(function(err, documents) {
    // Here is where we decide what to do with the query results
    if (err) throw err;
    console.log(documents);
    db.close();
  });
});

Output

{ _id: 5a4c5ffaeb092f0c1daac8b4, name: 'Jenny', age: 10 }

I don't want _id and its value in the output.

like image 472
mayank Avatar asked Nov 29 '25 07:11

mayank


1 Answers

Fields should be defined as part of the options (take a look into documentation).

Your code should look like this:

...
parrots.find({
  age: {
    $gt: parseInt(process.argv[2])
  }
}, {
  fields: {
    name: 1,
    age: 1,
    _id: 0
  }
})
...
like image 99
Neodan Avatar answered Dec 02 '25 04:12

Neodan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!