CRUD Operations in MongoDB / Perform CRUD Operations

Finding Documents in a MongoDB Collection

Review the following code, which demonstrates how to query documents in MongoDB.

Find a Single Document with Equality

To find a single document matching a condition, use the findOne() command with the $eq operator.

Here's an example:

db.books.findOne({title: {$eq: "Brave New World"}})

For equalities, you can use the implicit syntax of $eq to shorten your query:

db.books.findOne({title: "Brave New World"})

Find Multiple Documents with Equality

To find multiple documents matching a condition, use the find() command. You can use the $eq operator or the implicit syntax. Here’s an example of the latter:

db.books.find({publisher: "MongoDB Press"})

Find a Document by Using the $in Operator

Use the $in operator to select documents where the value of a field equals any value in the specified array. Here's an example:

db.zips.find({ city: { $in: ["PHOENIX", "CHICAGO"] } })