简体   繁体   中英

Unable to filter MongoDB collection

What's the proper way to filter a collection in MongoDB? I need to filter the array by the ID number.

 var collection = db.collection('blog'); try { collection.find().toArray(function(err, result) { if (err) { console.log('Error:', err); } else { res.render('blogEntry', { title: 'Blog Entry', session: req.session, blog: result }); db.close(); } }); } catch (Exception) { console.log('there was a problem when accessing collection'); } 

collection.find({ _id: "apple" }).toArray...

The method takes two parameters:

collection.find(query, projection) 

If you leave them empty, you fetch everything.

Here is the documentation

This is what I needed to do.

 var ObjectID = require('mongodb').ObjectID; collection.find({ _id: ObjectID(blogId) }).toArray(function(err, result) { callback(result); db.close(); }); 

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