mongodb 中使用 find() 語句進行查詢,可根據查詢條件篩選文檔。語法:db.collection.find(query, projection)。參數包括可選的查詢條件(query)和返回字段(projection)。用法:查找所有文檔、條件查找、指定返回字段、分頁查詢、排序結果、查找數組文檔、使用正則表達式和邏輯運算符進行復雜查詢。
MongoDB 查詢語句
MongoDB 使用稱為 find()
的查詢語句來檢索集合中的文檔。
語法
<code>db.collection.find(query, projection)</code>
登錄后復制
參數
query (可選): 用于過濾結果的查詢參數,例如 { name: "John" }
。
projection (可選): 用于指定要返回文檔中的哪些字段,例如 { name: 1, age: 1 }
。
用法
1. 查找所有文檔
<code>db.collection.find()</code>
登錄后復制
2. 根據條件查找文檔
<code>db.collection.find({ name: "John" })</code>
登錄后復制
3. 指定返回字段
<code>db.collection.find({}, { name: 1, age: 1 })</code>
登錄后復制
4. 分頁查詢
<code>db.collection.find().skip(10).limit(5)</code>
登錄后復制
5. 排序結果
<code>db.collection.find().sort({ name: 1 }) // Ascending order db.collection.find().sort({ name: -1 }) // Descending order</code>
登錄后復制
6. 查找文檔中的數組
<code>db.collection.find({"arrayField.field": "value"})</code>
登錄后復制
7. 使用正則表達式
<code>db.collection.find({ name: /John/i }) // case-insensitive match</code>
登錄后復制
8. 使用邏輯運算符
<code>db.collection.find({ $and: [{ name: "John" }, { age: { $gt: 18 }}] }) // AND operator</code>
登錄后復制