Query with Projection in MongoDB

>_ Projection

  • By default, queries in MongoDB return all fields in matching documents. To limit the amount of data that MongoDB sends to applications, you can include a projection document in the query operation.

    The projection document limits the fields to return for all matching documents. The projection document can specify the inclusion of fields or the exclusion of field and has the following form:

    {field1:<value>,field2: <value>...}
    The <value> can be any of the following:

    • 1 or true to include the field in the return documents.
    • 0 or false to exclude the field.

    A projection cannot contain both include and exclude specifications, except for the exclusion of the _id field. In projections that explicitly include fields, the _id field is the only field that you can explicitly exclude.

Assume these records are there in users collection

{ "_id" : ObjectId("5774c4b4fc520de27ab8745c"), "userid" :"Alex", "Age" : 25 }
{ "_id" : ObjectId("5774c4b4fc520de27ab8745d"), "userid" : "Andrew","Age" : 25}
{ "_id" : ObjectId("5774c4b4fc520de27ab8745e"),"userid" : "Andrew", "Age" : 44}
{ "_id" : ObjectId("5774c4b4fc520de27ab8745f"), "userid" : "Anderson","Age" : 40, "totalbet" : 0, "totalwin" : 0 }
{ "_id" : ObjectId("5774c4b4fc520de27ab87460"), "userid" : "McGraw","Age" : 45, "totalbet" : 1000, "totalwin" : 15000, "isOnline" :	false }
{ "_id" : ObjectId("5774c4b4fc520de27ab87461"),	"userid" : "Cock", "Age" : 45, " totalbet" : 1000, "totalwin" :
									15000, "isOnline" : true }
{ "_id" : ObjectId("5774c4b4fc520de27ab87462"), "userid" : "!@#", "Age" :25 }
  • >_ List all the users of users collection

     >db.users.find()

    Output:- Same as above assumed documents

    >_ List all the userids of users collection with _id

     >db.users.find({},{userid:1})

    Output:-

    { "_id" : ObjectId("5774c4b4fc520de27ab8745c"), "userid" :"Alex" }
    { "_id" : ObjectId("5774c4b4fc520de27ab8745d"),"userid" : "Andrew" }
    { "_id" : ObjectId("5774c4b4fc520de27ab8745e"), "userid" : "Andrew" }
    { "_id" : ObjectId("5774c4b4fc520de27ab8745f"), "userid" : "Anderson" }
    { "_id" : ObjectId("5774c4b4fc520de27ab87460"), "userid" : "McGraw" }
    { "_id" : ObjectId("5774c4b4fc520de27ab87461"), "userid" : "Cock" }
    { "_id" : ObjectId("5774c4b4fc520de27ab87462"), "userid" : "!@#" }
    

    >_ List all the userids,ages of users collection with out _id

     >db.users.find({},{userid:1,Age:1,_id:0})

    Output:-

    { "userid" :"Alex","Age":25 }
    { "userid" : "Andrew","Age":25 }
    { "userid" : "Andrew","Age":44 }
    { "userid" : "Anderson","Age":40 }
    { "userid" : "McGraw","Age":45 }
    { "userid" : "Cock","Age":45 }
    { "userid" : "!@#","Age":25}