Retrieving data in MongoDB

Using Projection to Limit Set of Fields Retrieved

Situation: You want to query a list of discordHandles or customerNames from a collection of documents (list of objects) and you don’t want every field.

Returning only one field in a document

# list only customer names without their id
db.customers.find({}, {customerName: 1, _id: 0}).pretty()

# list discord handles without the id
db.bounties.find({}, {"createdBy.discordHandle": 1, _id: 0}).pretty()

Using comparison operators to limit number of documents retrieved

# list all bounties with reward amount greater than 100
db.bounties.find({"reward.amount": {$gt: 100}}).pretty()

# list all bounties with reward less than 100
db.bounties.find({"reward.amount": {$lt: 100}}).pretty()

For more content on data science, R, and Python find me on Twitter.

Previous
Next