MongoDB data query can use the following commands: find(): query documents based on conditions. Query conditions: Specify conditions, such as document attributes, arrays, etc. Projection: Specify the return field, such as { title: 1, author: 1 }. Sorting: Specify the sorting field and order, such as { publishedDate: 1 }. Limit: Specify the number of documents returned, such as limit(5).
MongoDB data query
Data query in MongoDB can be performed through the following command:
find()
find()
command is used to search for documents that meet specific conditions. The syntax is:
<code>db.collection.find({ <查询条件> })</code>
Query conditions
Query conditions specify the conditions of the document to be found. Query conditions can be document attributes, arrays, nested documents, or other complex conditions.
Example:
Find documents whose title contains "MongoDB":
<code>db.articles.find({ title: /MongoDB/ })</code>
Find documents whose author is "John Doe":
<code>db.articles.find({ author: "John Doe" })</code>
Projection
Projection specifies the fields contained in the document to be returned. The syntax is:
<code>db.collection.find({ <查询条件> }, { <投影条件> })</code>
Projection conditions
Projection conditions specify the fields to be returned or excluded.
Example:
Return only the fields of title and author:
<code>db.articles.find({}, { title: 1, author: 1 })</code>
Sort
Sort specified The field by which to sort the documents. The syntax is:
<code>db.collection.find({ <查询条件> }).sort({ <排序条件> })</code>
Sort conditions
Sort conditions specify the sort order of fields. 1 means ascending order, -1 means descending order.
Example:
Sort in ascending order by release date:
<code>db.articles.find({}).sort({ publishedDate: 1 })</code>
Limitations
Limitations specify what to return number of documents. The syntax is:
<code>db.collection.find({ <查询条件> }).limit(<数量>)</code>
Example:
Limit the first 5 documents returned:
<code>db.articles.find({}).limit(5)</code>
The above is the detailed content of How to query data in mongodb. For more information, please follow other related articles on the PHP Chinese website!