Friday 20 February 2015

mongoDB : findOne : To get one document


“findOne” method returns one document, that satisfies query criteria.
Syntax
db.collection.findOne(<criteria>, <projection>)


Without specifying criteria and projection

> db.employee.findOne()
{
        "_id" : ObjectId("54b9485dfda21cabf10932cd"),
        "id" : 1,
        "firstName" : "Joel",
        "lastName" : "chelli"
}


By specifying criteria
> db.employee.findOne({"firstName" : "Ritwik"})
{
        "_id" : ObjectId("54b9485dfda21cabf10932d0"),
        "id" : 4,
        "firstName" : "Ritwik",
        "lastName" : "Mohenthy"
}

Above snippet returns one document where “firstName” is “Ritwik”.


By specifying criteria and projection

You can choose what columns you want to be in result by specifying projection criteria.
> db.employee.findOne({"firstName" : "Ritwik"}, {"firstName" : true})
{ "_id" : ObjectId("54b9485dfda21cabf10932d0"), "firstName" : "Ritwik" }


As you observe above snippet, I asked for column “firstName” in the result, but mongo shell display “_id” field also. It is because, “_id” will come by default in the result, you can disable this by specifying explicitly.
 
> db.employee.findOne({"firstName" : "Ritwik"}, {"firstName" : true, "_id" : false})
{ "firstName" : "Ritwik" }

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment