mongodb: find and projection

This post discusses find and projection in mongoDB.

version

bash-3.2$ mongo
MongoDB shell version v3.4.6
connecting to: mongodb://127.0.0.1:27017

insert document into a collection
Add four documents into test.member collection.

> show dbs
admin  0.000GB
local  0.000GB
> db
test
> db.member.insert({name: 'chengyihe'})
WriteResult({ "nInserted" : 1 })
> db.member.insert({name: 'woody'})
WriteResult({ "nInserted" : 1 })
> db.member.insert({name: 'max'})
WriteResult({ "nInserted" : 1 })
> db.member.insert({name: 'daniel'})
WriteResult({ "nInserted" : 1 })

show documents in a collection with projection

  • db.member.find() list all documents with all fields.
  • db.member.find({},{_id: 0, name: 1}) list all documents with only name field.
  • > db.member.find()
    { "_id" : ObjectId("5978cda6558e820054f7be9c"), "name" : "chengyihe" }
    { "_id" : ObjectId("5978cdac558e820054f7be9d"), "name" : "woody" }
    { "_id" : ObjectId("5978cdaf558e820054f7be9e"), "name" : "max" }
    { "_id" : ObjectId("5978cdb2558e820054f7be9f"), "name" : "daniel" }
    > db.member.find({},{_id: 0, name: 1})
    { "name" : "chengyihe" }
    { "name" : "woody" }
    { "name" : "max" }
    { "name" : "daniel" }
    

    conclusion
    The post shows how to use projection operator to show only some fields of satisfied documents.

    Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: