search
HomeDatabaseMysql TutorialIntroduction to common Query operations in MongoDB (with code)

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

Introduction to common Query operations in MongoDB (with code)

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

类型如下:

Introduction to common Query operations in MongoDB (with code)

详细文档请看: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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
How does MySQL's licensing compare to other database systems?How does MySQL's licensing compare to other database systems?Apr 25, 2025 am 12:26 AM

MySQL uses a GPL license. 1) The GPL license allows the free use, modification and distribution of MySQL, but the modified distribution must comply with GPL. 2) Commercial licenses can avoid public modifications and are suitable for commercial applications that require confidentiality.

When would you choose InnoDB over MyISAM, and vice versa?When would you choose InnoDB over MyISAM, and vice versa?Apr 25, 2025 am 12:22 AM

The situations when choosing InnoDB instead of MyISAM include: 1) transaction support, 2) high concurrency environment, 3) high data consistency; conversely, the situation when choosing MyISAM includes: 1) mainly read operations, 2) no transaction support is required. InnoDB is suitable for applications that require high data consistency and transaction processing, such as e-commerce platforms, while MyISAM is suitable for read-intensive and transaction-free applications such as blog systems.

Explain the purpose of foreign keys in MySQL.Explain the purpose of foreign keys in MySQL.Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

What are the different types of indexes in MySQL?What are the different types of indexes in MySQL?Apr 25, 2025 am 12:12 AM

There are four main index types in MySQL: B-Tree index, hash index, full-text index and spatial index. 1.B-Tree index is suitable for range query, sorting and grouping, and is suitable for creation on the name column of the employees table. 2. Hash index is suitable for equivalent queries and is suitable for creation on the id column of the hash_table table of the MEMORY storage engine. 3. Full text index is used for text search, suitable for creation on the content column of the articles table. 4. Spatial index is used for geospatial query, suitable for creation on geom columns of locations table.

How do you create an index in MySQL?How do you create an index in MySQL?Apr 25, 2025 am 12:06 AM

TocreateanindexinMySQL,usetheCREATEINDEXstatement.1)Forasinglecolumn,use"CREATEINDEXidx_lastnameONemployees(lastname);"2)Foracompositeindex,use"CREATEINDEXidx_nameONemployees(lastname,firstname);"3)Forauniqueindex,use"CREATEU

How does MySQL differ from SQLite?How does MySQL differ from SQLite?Apr 24, 2025 am 12:12 AM

The main difference between MySQL and SQLite is the design concept and usage scenarios: 1. MySQL is suitable for large applications and enterprise-level solutions, supporting high performance and high concurrency; 2. SQLite is suitable for mobile applications and desktop software, lightweight and easy to embed.

What are indexes in MySQL, and how do they improve performance?What are indexes in MySQL, and how do they improve performance?Apr 24, 2025 am 12:09 AM

Indexes in MySQL are an ordered structure of one or more columns in a database table, used to speed up data retrieval. 1) Indexes improve query speed by reducing the amount of scanned data. 2) B-Tree index uses a balanced tree structure, which is suitable for range query and sorting. 3) Use CREATEINDEX statements to create indexes, such as CREATEINDEXidx_customer_idONorders(customer_id). 4) Composite indexes can optimize multi-column queries, such as CREATEINDEXidx_customer_orderONorders(customer_id,order_date). 5) Use EXPLAIN to analyze query plans and avoid

Explain how to use transactions in MySQL to ensure data consistency.Explain how to use transactions in MySQL to ensure data consistency.Apr 24, 2025 am 12:09 AM

Using transactions in MySQL ensures data consistency. 1) Start the transaction through STARTTRANSACTION, and then execute SQL operations and submit it with COMMIT or ROLLBACK. 2) Use SAVEPOINT to set a save point to allow partial rollback. 3) Performance optimization suggestions include shortening transaction time, avoiding large-scale queries and using isolation levels reasonably.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)