MongoDB basics for everyone – Part 5 Using find() and findOne()

You would have noticed from the previous examples that the find() command returns a document from our tutorial collection with a rather strange looking _id field.
The _id field is always there and should be a unique identifier for the particular record in the collection. You have the option of overriding the _id field with an id of your choice, but please do keep in mind that it is required to be unique.

The find() command in MongoDB will always return a cursor. You can assign the cursor to a variable in Javascript to demonstrate this right in the mongo shell!

Take the following as an example:

first, let’s add another document to our collection:

db.testcollection.insert({“test”: 2})

now, we will assign find() to a Javascript variable:

var mycursor = db.testcollection.find()

as you can see, there is no output, but we can check that the cursor has indeed found something with

mycursor.hasNext()

which should return true. Now let us iterate through the documents found and display them as we go along

mycursor.next()

will display the next document that the cursor has found, so we can manually have a look at all the documents by using hasNext() and next() in succession. Once we reach the end of the found documents in our cursor,

hasNext()

will simply display false and we can stop the iteration. A good homework assignment here would be to write a quick Javascript function that will iterate through all of the found documents and display them as find() does.

(Spoiler alert) Answer:

for( var c = db.testcollection.find(); c.hasNext(); ) {
print( c.next());
}

or use built in

forEach()

In later versions of MongoDB find() will automatically paginate the resultset and allow you to use the it command within the shell to iterate over the documents found.

The

findOne()

command is very similar to

find()

, except that it will not return a cursor, but it will only return a single document. In general, it will always return the first document that satisfies all of the selection criteria and sorting criteria, which we will explore a little more in the next post.

Summary
Author Rating
4
Software Name
MongoDB
Operating System
All
Price
0

One thought on “MongoDB basics for everyone – Part 5 Using find() and findOne()

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>