Let's find all the books that were published by Dover Publications. The following code shows us how to accomplish this:
> db.find({ publisher : "Dover Publications"})
{ "_id" : ObjectId("4e86e45efed0eb0be0000010"), "author_id" : ObjectId("4e86e4b6fed0eb0be0000011"), "category_ids" : [
ObjectId("4e86e4cbfed0eb0be0000012"),
ObjectId("4e86e4d9fed0eb0be0000013")
], "name" : "Oliver Twist", "publisher" : "Dover Publications", "reviews" : [
{
"comment" : "Fast paced book!",
"username" : "Gautam",
"_id" : ObjectId("4e86f68bfed0eb0be0000018")
},
{
"comment" : "Excellent literature",
"username" : "Tom",
"_id" : ObjectId("4e86f6fffed0eb0be000001a")
}
], "votes" : [ { "username" : "Gautam", "rating" : 3 } ] }
We have just fired a simple find()
query on a collection to help us get the relevant documents from the database. We can also configure the parameters in find()
to get more specific details. To see what specific parameters find()
has, issue the following command:
> db.books.find
function (query, fields, limit, skip) {
return new DBQuery(this._mongo, this._db, this, this._fullName, this._massageObject(query), fields, limit, skip);
}
The configuration parameters for find()
in the preceding code are explained as follows:
query:
This is the selection criteria. For example, { publisher: "Dover Publications" }
as we had mentioned earlier. This is similar to the WHERE
clause in a relational query.fields:
These are the fields which we want selected. This is similar to the SELECT
part of a query in a relational query. By default, all fields would be selected, so SELECT *
is the default. In MongoDB we can specify inclusion as well as exclusion of fields. We will see an example of this shortly.limit:
This represents the number of elements we want returned from the query. This is similar to the LIMIT
part of a relational query.skip:
This is the number of elements the query should skip before collecting results. This is similar to the OFFSET
part of a relational query.How do we search for books that are published by Dover Publications and written by Mark Twain?
Hint: We need to fire two queries. The first one would be to find the author by name "Mark Twain". Then using that ObjectId
, we can find the books written by that author and published by Dover Publications.
18.191.180.124