Introduction 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
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!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

.NET 4.0 is used to create a variety of applications and it provides application developers with rich features including: object-oriented programming, flexibility, powerful architecture, cloud computing integration, performance optimization, extensive libraries, security, Scalability, data access, and mobile development support.

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

MongoDB and relational database: In-depth comparison This article will explore in-depth the differences between NoSQL database MongoDB and traditional relational databases (such as MySQL and SQLServer). Relational databases use table structures of rows and columns to organize data, while MongoDB uses flexible document-oriented models to better suit the needs of modern applications. Mainly differentiates data structures: Relational databases use predefined schema tables to store data, and relationships between tables are established through primary keys and foreign keys; MongoDB uses JSON-like BSON documents to store them in a collection, and each document structure can be independently changed to achieve pattern-free design. Architectural design: Relational databases need to pre-defined fixed schema; MongoDB supports

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

PiNetwork is about to launch PiBank, a revolutionary mobile banking platform! PiNetwork today released a major update on Elmahrosa (Face) PIMISRBank, referred to as PiBank, which perfectly integrates traditional banking services with PiNetwork cryptocurrency functions to realize the atomic exchange of fiat currencies and cryptocurrencies (supports the swap between fiat currencies such as the US dollar, euro, and Indonesian rupiah with cryptocurrencies such as PiCoin, USDT, and USDC). What is the charm of PiBank? Let's find out! PiBank's main functions: One-stop management of bank accounts and cryptocurrency assets. Support real-time transactions and adopt biospecies
