Home >Database >MongoDB >How to query data in mongodb

How to query data in mongodb

下次还敢
下次还敢Original
2024-04-02 11:57:161096browse

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).

How to query data in mongodb

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn