Tuesday, March 31, 2015

MongoDB find() and findOne() methods



     In  MongoDB CRUD operation find() and findOne() methods are used to read a documents from the collections. Lets study this methods with example. 

1. find() : 
                  The most basic operation to query documents out of the database is called find(). MongoDB find() method returns all documents present in the database.
 For example, Here I have student database and collection name is grades which has 800 documents. After executing this query it returns first 10 documents and it ask for next 10 documents. If you want more documents type "it" next 10 documents will get display.

    find() method can take some arguments. You can filter result by adding search criteria. For example in "grades" collection there are "homework","quiz" and "exam " type of documents. If I want only "exam" type . The query will be db.grades.find({''type'' :''exam''}).




       We can also add multiple fields in criteria but both the criteria should match. Like here I have selected students with type :exam and you can also include and exclude fields if you want by making field name true or false, here I excluded object id field.





  2. findOne():

 This method also retrieves the data but it returns only one document at a time. Lets see following example fineOne() without argument returns very first document from the collection.



  We can also add criteria in findOne() method like find() method. In following example only document with the "student_id" : 112 is return as specified in criteria.




         









No comments:

Post a Comment