Jerry
Jerry

Reputation: 175

MongoDB. Selecting only 1 column from table

I have the following database

{"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":"Jamal David","followers":6531, "body":"my text 4","confirmed":"yes"}
{"userName":"jane fonda","followers":3941, "body":"my text 5","confirmed":"no"}

I need to count number of followers whose name starts with Ja (case-insensitive)

This is what I'm trying to do:

db.test.find({$and:[{followers:{$gte:0}}, {"userName":{$regex :/^Ja/i}}]})

but it gives me bach the whole matching string while I need only the userName. Could you help me please?

Upvotes: 1

Views: 165

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

Add projection to query

db.test.find({followers:{$gte:0}, userName:{$regex :/^Ja/i}}, {_id:0, userName:1})

Keep in mind:

  • find always returns _id unless you specify _id:0 in projection.
  • $and operation is used implicitly - you don't need it to specify filters for several fields

Upvotes: 1

Related Questions