Saturday 21 February 2015

mongoDB : Projection


By default mongoDB returns all the fields of the document, that match query criteria. By using projection, you can ask for the fields you are interested.

In projection criteria of find query, set the field values to zero (0), if you don’t want those columns in your result.

db.employee.find({},{_id : 0})
Get all the columns other than “_id”.

db.employee.find({},{_id : 0, firstName:0})
Get all the columns other than “_id”, “firstName”

>db.employee.insert(
 [
   {
     "id": 1,
     "firstName": "Joel",
     "lastName": "chelli"
   },
   {
     "id": 2,
     "firstName": "Ananad",
     "lastName": "Bandaru"
   },
   {
     "id": 3,
     "firstName": "Gopi",
     "lastName": "Battu"
   },
   {
     "id": 4,
     "firstName": "Ritwik",
     "lastName": "Mohenthy"
   }
 ]
 )
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 4,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
>
> db.employee.find()
{ "_id" : ObjectId("54b348e01deb1f5f980626a2"), "id" : 1, "firstName" : "Joel", "lastName" : "chelli" }
{ "_id" : ObjectId("54b348e01deb1f5f980626a3"), "id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru" }
{ "_id" : ObjectId("54b348e01deb1f5f980626a4"), "id" : 3, "firstName" : "Gopi", "lastName" : "Battu" }
{ "_id" : ObjectId("54b348e01deb1f5f980626a5"), "id" : 4, "firstName" : "Ritwik", "lastName" : "Mohenthy" }
>
>
> db.employee.find({},{_id : 0})
{ "id" : 1, "firstName" : "Joel", "lastName" : "chelli" }
{ "id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru" }
{ "id" : 3, "firstName" : "Gopi", "lastName" : "Battu" }
{ "id" : 4, "firstName" : "Ritwik", "lastName" : "Mohenthy" }
>
>
> db.employee.find({},{_id : 0, firstName:0})
{ "id" : 1, "lastName" : "chelli" }
{ "id" : 2, "lastName" : "Bandaru" }
{ "id" : 3, "lastName" : "Battu" }
{ "id" : 4, "lastName" : "Mohenthy" }

 

db.employee.find({},{id : 1, firstName: 1})

Select only id and firstName.

> db.employee.find({},{id : 1, firstName: 1})
{ "_id" : ObjectId("60bcd0dd8251689f64fb3eee"), "id" : 1, "firstName" : "Joel" }
{ "_id" : ObjectId("60bcd0dd8251689f64fb3eef"), "id" : 2, "firstName" : "Ananad" }
{ "_id" : ObjectId("60bcd0dd8251689f64fb3ef0"), "id" : 3, "firstName" : "Gopi" }
{ "_id" : ObjectId("60bcd0dd8251689f64fb3ef1"), "id" : 4, "firstName" : "Ritwik" }
> 
As you see the output, _id is added by default in all the documents. If you don't want _id in the result, you can explcitly specify in the query (_id : 0).
> db.employee.find({},{id : 1, firstName: 1, _id : 0})
{ "id" : 1, "firstName" : "Joel" }
{ "id" : 2, "firstName" : "Ananad" }
{ "id" : 3, "firstName" : "Gopi" }
{ "id" : 4, "firstName" : "Ritwik" }



 
 
 
 
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment