How to remove _id when I print fields using printjson()?

285 views Asked by At
db.events.find().forEach(function(doc)
{
    var iso_date = new Date(doc.starts_at);
    if(iso_date>= new Date() && iso_date<= new Date(new Date().setDate(new 
     Date().getDate()+4))){
        printjson(doc);
    }
})

I am unable to remove _id field using printjson() in MongoDB. I am printing fields based on a particular condition which I have handled using JavaScript. While printing using printjson(), I can't remove _id field. Is there a way to remove _id while printing using printjson()?

2

There are 2 answers

0
matthPen On BEST ANSWER

Simply use projection to avoid returning _id in db results :

db.events.find(
  {starts_at: {$gte: Date.now(), $lte: new Date().setDate(4)}},
  {_id:0} 
)
.forEach(function(doc)
{
    printjson(doc);
});
0
virgiliogm On

As JME pointed out in the comment to your question, you can delete the _id field before printing the document. On the other hand, the comparison of dates could be something simpler and, more importantly, you should do it in the query to treat only the documents you want instead of looping through all the documents in the database, so I think your code could look like this:

db.events.find({starts_at: {$gte: Date.now(), $lte: new Date().setDate(4)}}).forEach(function(doc)
{
    delete doc._id;
    printjson(doc);
});