Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting only a single field from MongoDB

Tags:

mongodb

This is my sample database in MongoDB

{"userName":"John Smith", "followers":8075,"body":"my text 1","confirmed":"no"}
{"userName":"James Bond", "followers":819, "body":"my text 2", "confirmed":"yes"}
{"userName":"Julia Roberts","followers":3882,"body":"my text 3","confirmed":"yes"}
{"userName":"Matt Damon","followers":6531, "body":"my text 4","confirmed":"yes"}
{"userName":"Amy Adams","followers":3941, "body":"my text 5","confirmed":"no"}

I need to select the userName with more than 3000 followers and where account was confirmed. This is what I'm trying to do:

db.collection.find( { $and:[{followers: { $gt: 3000 } },  {"confirmed" : "yes"}] })

But this way gives me whole matching lines while I only need userName. Can you please advice?

like image 636
Jerry Avatar asked Mar 21 '26 16:03

Jerry


1 Answers

You have to specify the return fields as such;

db.collection.find( { $and:[{followers: { $gt: 3000 } }, {"confirmed" : "yes"}] }, {userName: 1, _id: 0})

More details can be found here

Also if you'd want to suppress _id field, you'd wish to add _id: 0. Details of which is here

like image 54
buræquete Avatar answered Mar 24 '26 12:03

buræquete



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!