W3Schools is a go-to resource for web developers, providing tutorials and references for various technologies, including MongoDB. MongoDB is a popular NoSQL database, and understanding how to query it efficiently is crucial for any developer working with this database. In this article, we'll delve into MongoDB queries, using examples from W3Schools to illustrate key concepts.

Before diving into queries, let's assume we have a MongoDB collection named 'mycol' with the following documents:

{
"_id": 1,
"name": "John",
"age": 30,
"city": "New York"
},
{
"_id": 2,
"name": "Alice",
"age": 25,
"city": "Los Angeles"
}
Basic Queries
MongoDB uses the find() method to query documents. Let's start with some basic queries.

Query by Field
The find() method takes a query document as its argument. To query for documents with a specific field value, you can use a query document where the field name is set to the desired value:

db.mycol.find({ "city": "New York" })
This query returns the document with _id: 1, as the 'city' field is set to 'New York'.
Query Multiple Fields
You can query for documents that match multiple fields by specifying them in the query document. All specified fields must match:

db.mycol.find({
"age": 30,
"city": "New York"
})
This query returns the document with _id: 1, as it matches both the 'age' and 'city' fields.
Modifiers
MongoDB provides modifiers to control query results. Here are a few key modifiers.

Limit()
The limit() method restricts the number of documents returned by a query. It takes an integer as an argument, specifying the maximum number of documents to return:




















db.mycol.find().limit(1)
This query returns the first document in the collection.
Skip()
The skip() method returns all documents except the first 'n' documents, where 'n' is the argument passed. It's useful for pagination:
db.mycol.find().skip(1)
This query skips the first document, returning all documents except the first one.
Practical querying in MongoDB requires understanding more advanced queries, but these basic queries and modifiers should give you a solid foundation. Now that you've seen some examples, why not try writing a few queries of your own on W3Schools MongoDB playground? Happy coding!