This article brings you an introduction to the common Query operations of MongoDB (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Foreword: The visualization tool used is Studio 3T, official website-->https://studio3t.com/
Version number: MongoDB shell version v3.4.2
How to use: https:/ /blog.csdn.net/weixin_...
What to watch: focus on the operators.
How to search: Press ctrl F on this page and enter keywords to search
1. Commonly used Query
For the convenience of operation, delete all documents before inserting the original data ( Please operate with caution in the project! ):
db.getCollection("inventory").deleteMany({})
0. View all documents
db.getCollection("inventory").find({})
1. Object search
1.1. Original data
db.inventory.insertMany( [
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);
1.2. Find documents where size.h is equal to 14, size.w is equal to 21, and size.uom is equal to cm
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
1.3. Find size.uom is equal to Documentation for in
db.inventory.find( { "size.uom": "in" } )
Note: When looking up individual object properties, be sure to include quotes!
1.4. Find and return the specified fields in the object
db.inventory.find(
{ status: "A" },
{ item: 1, status: 1, "size.uom": 1 }
)
1.5. Find and filter the specified fields in the object
db.inventory.find(
{ status: "A" },
{ "size.uom": 0 }
)
2. Array search
2.1. Original data
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);
2.2. Find documents with tags=["red", "blank"]
db.inventory.find( { tags: ["red", "blank"] } )
Note: It is not an inclusion relationship, that is tags: ["red", "blank", "plain"] are not included
2.3. Find documents whose tags contain red
db.inventory.find( { tags: "red" } )
Note: You cannot write db.inventory.find( { tags: ["red"] } ) like this, which means you are looking for documents whose tags are red
3. Search for objects contained in arrays
3.1. Original data
db.inventory.insertMany( [
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
3.2. Find an object in the array that meets the conditions (not included). As long as there is an object in the array that meets the conditions, the entire array will be returned.
db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )
Must strictly follow the order of the fields. If the order of the fields is changed, cannot be found , as follows:
db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )
3.3. Find the element object in the array, there is one The qty=5 of the element object, or the warehouse=A
db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )
3.4. Find the object in the array and return a certain attribute of the object
db.inventory.find( { status: "A" }, { item: 1, status: 1, "instock.qty": 1 } )
4. Ordinary search
4.1. Original data
db.inventory.insertMany( [
{ item: "journal", status: "A", size: { h: 14, w: 21, uom: "cm" }, instock: [ { warehouse: "A", qty: 5 } ] },
{ item: "notebook", status: "A", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", status: "D", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "A", qty: 60 } ] },
{ item: "planner", status: "D", size: { h: 22.85, w: 30, uom: "cm" }, instock: [ { warehouse: "A", qty: 40 } ] },
{ item: "postcard", status: "A", size: { h: 10, w: 15.25, uom: "cm" }, instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
4.2. Query and return specified fields
Under the condition of status=A, return _id, item, status fields
db.inventory.find( { status: "A" }, { item: 1, status: 1 } )
Result:
{ "_id" : ObjectId("5c91cd53e98d5972748780e1"),
"item" : "journal",
"status" : "A"}
// ----------------------------------------------
{ "_id" : ObjectId("5c91cd53e98d5972748780e2"),
"item" : "notebook",
"status" : "A"}
// ----------------------------------------------
{ "_id" : ObjectId("5c91cd53e98d5972748780e5"),
"item" : "postcard",
"status" : "A"}
4.3. From 4.2, it can be seen that _id is automatically carried and can be removed, as follows
Query without (removed) id:
db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )
Note: In addition to the id that can be filtered out while retaining other fields, other fields cannot be 0 while also writing 1
For example:
db.inventory.find( { status: "A" }, { item: 1, status: 0 } ) will report an error

4.4. Exclude specific fields and return other fields
db.inventory.find( { status: "A" }, { status: 0, instock: 0 } )
5. Find null or Non-existent key
5.1. Original data
db.inventory.insertMany([
{ _id: 1, item: null },
{ _id: 2 }
])
5.2. Find documents where item is null, or documents that do not contain item
db.inventory.find( { item: null } )
2. Operators
1、$lt less than less than
1.1、Original data
db.inventory.insertMany( [
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);
1.2、Find the document collection with "size.h" less than 15
db.inventory.find( { "size.h": { $lt: 15 } } ) 1.3. Use $lt with AND
Find documents where size.h is less than 15, size.uom is in, and status is D
db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" } )
2.$lte less than equal is less than or equal to
2.1, original data
db.inventory.insertMany( [
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
2.2. Find documents with instock.qty less than or equal to 20, and return the entire array as long as one object in the array meets the conditions
db.inventory.find( { 'instock.qty': { $lte: 20 } } )
3、$gt greater than
3.1、Original data
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);
3.2、Find documents with dim_cm greater than 25
db.inventory.find( { dim_cm: { $gt: 25 } } )
Note: as long as it contains Arrays of elements greater than 25 are all qualified
3.3. Find documents whose dim_cm is greater than 15, or less than 20, or both greater than 15 and less than 20
db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )
3.4 , Find documents where dim_cm is both greater than 22 and less than 30 (it is to judge whether a certain element of the array is greater than 22 and less than 30, rather than judging all elements of the array)
db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )
3.5. According to the array position Search
Find documents where the second element of dim_cm is greater than 25
db.inventory.find( { "dim_cm.1": { $gt: 25 } } )
4, $size Search according to the length of the array
Find tags Document with a length of 3
db.inventory.find( { "tags": { $size: 3 } } )
5, $gte is greater than or equal to
5.1, Original data
db.inventory.insertMany( [
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
5.2, Find the first element of the array A collection of documents whose qty (object) is greater than or equal to 20
db.inventory.find( { 'instock.0.qty': { $gte: 20 } } )
6. $elemMatch object attribute matching
6.1. Search in the array for qty=5, warehouse="A " object and return the document collection
db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )
6.2. Find the document collection in the array that matches qty greater than 10 and less than or equal to 20
db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )
如果不使用 $elemMatch 的话,就表示 qty 大于 10 或者小于等于 20,官方文档意思是,不在数组的某一个元素找 既满足条件 A 又满足条件 B 的 qty,而是在数组的所有元素上找,满足条件 A 或满足条件 B 的 qty
db.inventory.find( { "instock.qty": { $gt: 10, $lte: 20 } } )
7、$slice 返回数组特定位置的元素
7.1、原数据
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);
7.2、查找并返回 tags 数组的最后一个元素
db.inventory.find( { item: "journal" }, { item: 1, qty: 0, tags: { $slice: -1 } } )
结果:
{
"_id" : ObjectId("5c91dce5e98d5972748780e6"),
"item" : "journal",
"tags" : [
"red"
]
}
8、$type 返回指定类型的元素
8.1、原数据
db.inventory.insertMany([
{ _id: 1, item: null },
{ _id: 2 }
])
8.2、返回 null 类型的数据
db.inventory.find( { item : { $type: 10 } } )
类型如下:

详细文档请看:https://docs.mongodb.com/manu...
9、$exists 返回存在/不存在的键
查找不存在 item 键的数据
db.inventory.find( { item : { $exists: false } } )
10、$all 包含
10.1、原数据
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);
10.2、查找 tags 数组包含 ["red", "blank"] 的文档
db.inventory.find( { tags: { $all: ["red", "blank"] } } )
综上:
数组用的:$all、$size、$slice
对象用的:$elemMatch
Query查询的详细文档请看:https://docs.mongodb.com/manu...
Operator的详细文档请看:https://docs.mongodb.com/manu...
本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的mongodb视频教程栏目!
The above is the detailed content of Introduction to common Query operations in MongoDB (with code). For more information, please follow other related articles on the PHP Chinese website!
Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AMInnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.
What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AMKey metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.
What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AMUsingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB
Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Apr 15, 2025 am 12:11 AMMySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.
MySQL vs. Other Databases: Comparing the OptionsApr 15, 2025 am 12:08 AMMySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.
How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AMMySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.
MySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AMThe MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.
Real-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AMMySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools

Dreamweaver CS6
Visual web development tools






