Jerry
Jerry

Reputation: 175

Selecting only a single field from 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?

Upvotes: 3

Views: 84

Answers (3)

Pramod Rajapaksha
Pramod Rajapaksha

Reputation: 1

use

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

Upvotes: -1

Vaibhav Patil
Vaibhav Patil

Reputation: 3023

You can try

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

Upvotes: 0

buræquete
buræquete

Reputation: 14698

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

Upvotes: 2

Related Questions