3

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?

buræquete
  • 14,226
  • 4
  • 44
  • 89
Jerry
  • 175
  • 2
  • 3
  • 11
  • Possible duplicate of [How to select a single field in MongoDB?](https://stackoverflow.com/questions/25589113/how-to-select-a-single-field-in-mongodb) – ponury-kostek Nov 07 '18 at 16:30

3 Answers3

2

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

buræquete
  • 14,226
  • 4
  • 44
  • 89
0

You can try

db.collection.find( { $and:[{followers: { $gt: 3000 } },  {"confirmed" : "yes"}] }).select({"userName":1})
Vaibhav Patil
  • 2,603
  • 4
  • 14
  • 22
-1

use

db.collection.find( { $and:[{followers: { $gt: 3000 } }, {"confirmed" : "yes"}] }, {"userName" :  1, _id : 0 })
buræquete
  • 14,226
  • 4
  • 44
  • 89
  • 1
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Dr Rob Lang Mar 14 '17 at 00:11