当前位置:网站首页>04 summary of various query operations and aggregation operations of mongodb
04 summary of various query operations and aggregation operations of mongodb
2022-06-28 04:05:00 【cui_ yonghua】
Catalog : The basic chapter ( Can solve the problem of 80 The problem of )
01 MongoDB Overview 、 Application scenarios 、 Download mode 、 Connection mode and development history, etc
02 MongoDB data type 、 Key concepts and shell Commonly used instructions
03 MongoDB Various additions to documents 、 to update 、 Delete operation summary
04 MongoDB Various query operations And summary of aggregation operations
05 MongoDB Summarize the various operations of the column
python3 operation MongoDB Various cases of
One . Use find() Method to query documents
Grammar format : db.collection.find(query, projection)
explain : find() Method to display all documents in an unstructured manner , Parameters can be specified :
query: Optional , Use the query operator to specify the query criteria ;projection: Optional , Use the projection operator to specify the returned key . Returns all key values in the document when queried , Simply omit the parameter ( The default is omitted ).
Case study 1: Such as directed set user_demo The query name in is zhangsan Users of :
db.user_demo.find({
'name':'zhangsan'})
# amount to sql Medium
select * from user_demo where name = "zhangsan";
Case study 2: Specifies which keys are returned
db.article.find({
}, {
"title": 1, "author": 1})
# amount to sql Medium
select title, author from article;
except find() Out of the way , One more findOne() Method , It returns only one document .
Two . AND Query and OR Inquire about
2.1 AND Inquire about
AND Query syntax format : db.col.find({key1:value1, key2:value2})
Case study 1: Such as directed set user_demo The query name in is zhangsan And age by 20 The data of :
db.user_demo.find({
'name':'zhangsan', 'age': 20})
# amount to sql Medium
select * from user_demo where name = "zhangsan" and age = 20;
2.2 OR Inquire about
OR Query syntax format :
db.col.find(
{
$or: [
{
key1: value1}, {
key2:value2}
]
}
)
Case study 2: Such as directed set user_demo The query name in is zhangsan Users or age by 20 The data of :
db.user_demo.find({
$or:[{
'name':'zhangsan', 'age': 20}]})
# amount to sql Medium
select * from article where name = "zhangsan" or age = 20;
Case study 3: AND and OR Joint use cases , Similar to the conventional SQL Statement for :
db.col.find({
"likes": {
$gt:50}, $or: [{
"by": "xx course "},{
"title": "MongoDB course "}]})
# amount to sql Medium
select * from col where likes>50 AND (by = 'xx course ' OR title = 'MongoDB course ');
3、 ... and . Conditional operators
3.1 Comparison conditions
MongoDB The conditional operators in are :
(>) Greater than - $gt
(<) Less than - $lt
(>=) Greater than or equal to - $gte
(<= ) Less than or equal to - $lte
Case study 1: obtain “col” Collection “likes” Greater than 100 The data of :
db.col.find({
likes : {
$gt : 100}})
# amount to sql Medium
select * from col where likes > 100;
Case study 2: obtain "col" Collection “likes” Greater than or equal to 100 The data of :
db.col.find({
likes : {
$gte : 100}})
# amount to sql Medium
select * from col where likes >= 100;
Case study 3: obtain "col" Collection “likes” Less than 150 The data of :
db.col.find({
likes : {
$lt : 150}})
# amount to sql Medium
select * from col where likes < 150;
Case study 4: obtain "col" Collection “likes” Less than or equal to 150 The data of :
db.col.find({
likes : {
$lte : 150}})
# amount to sql Medium
select * from col where likes <= 150;
Case study 5: obtain "col" Collection “likes” Greater than 100, Less than 200 The data of :
db.col.find({
likes : {
$lt :200, $gt : 100}})
# amount to sql Medium
select * from col where likes > 100 and likes < 200;
Case study 6: obtain "col" Collection “likes” It's not equal to 100 The data of :
db.col.find({
likes : {
"$ne": 100}})
# amount to sql Medium
select * from col where likes != 100;
3.2 in Conditions
select * from article where author in ("a", "b", "c")
# amount to sql Medium
db.article.find({
"author": {
"$in": ["a", "b", "c"]}})
3.3 like Conditions of the query
db.article.find({
"title": /mongodb/})
# amount to sql Medium
select * from article where title like "%mongodb%"
Four . limit() Methods and skip() Method
4.1 Control the number of returns limit() Method
Grammar format (limit):db.COLLECTION_NAME.find().limit(NUMBER)
For example, two records in the query document are displayed :
db.col.find({
},{
"title":1}).limit(2)
Except that it can be used limit() Method to read a specified amount of data , You can also use skip() Method to skip a specified amount of data ,skip Method also accepts a numeric parameter as the number of records to skip .
4.2 Skip the quantity skip() Method
Grammar format :db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
The following example shows only the second document data :
db.col.find({
},{
"title":1).limit(1).skip(1)
# The following is the skip before 5 Data , That is from the 6 Start to return to .
db.article.find().skip(5)
notes :skip() The default parameter of the method is 0 .
4.3 limit and skip combination
Can combine limit() and skip() To achieve paging effect :
db.article.find().skip(10).limit(20)
# amount to sql Medium
select * from article limit 10, 20;
5、 ... and . Sort sort() Method
stay MongoDB Use in sort() Method to sort the data .
sort() Method can be used to specify the sorting field by parameter , And use 1 and -1 To specify how to sort , among 1 Arrange... In ascending order , and -1 It's for descending order .
Grammar format :db.COLLECTION_NAME.find().sort({KEY:1})
If in col Data in the collection by field likes Descending order of :
db.col.find({
},{
"title":1}).sort({
"likes":-1})
# amount to sql Medium
select * from col where title = 1 order by likes desc;
Be careful :skip(), limilt(), sort() When the three are put together , The order of execution is first sort(), And then there was skip(), Finally, it shows limit().
6、 ... and . $type The operator
6.1 MongoDB The types that can be used in are shown in the following table :
- Double 1
- String 2
- Object 3
- Array 4
- Binary data 5
- Undefined 6 obsolete .
- Object id 7
- Boolean 8
- Date 9
- Null 10
- Regular Expression 11
- JavaScript 13
- Symbol 14
- JavaScript (with scope) 15
- 32-bit integer 16
- Timestamp 17
- 64-bit integer 18
- Min key 255 Query with -1.
- Max key 127
Case study : obtain “col” Collection title by String The data of :db.col.find({"title" : {$type : 2}}) or db.col.find({"title" : {$type : 'string'}})
6.2 Query of multiple elements
Case study : Only type Arrays exist at the same time mongodb and javascript Will match .
db.article.find({
"type": {
"$all": ["mongodb", "javascript"]}})
6.3 Limit array length query
Case study : Only the length of the array is 2 Will match , notes :type_list It must be an array
db.article.find({
"type_list": {
"$size": 2}})
6.4 Returns a specific quantity
When $slice When the parameter of is a , Represents the number of returns ; When it's an array , The first parameter is the offset , The second represents the number of returns :
Case study : Returns a specific quantity , notes :$slice For arrays
db.article.find({
"type": {
"$slice": 1}}) // Back to page 1 individual
db.article.find({
"type": {
"$slice": -1}}) // Go back to the last
db.article.find({
"type": {
"$slice": [20, 10]}}) // From 21 Start , return 10 individual , That is to say 21~30
For more types, please refer to :mongodb $type
7、 ... and . MongoDB Special sentences
7.1 Element match ($elemMatch)
If there is a field in the document whose value is an array , have access to $elemMatch To match elements in an array :
Case study : Only a=1 And b>2 Will match .
db.article.find({
"kown": {
"$elemMatch": {
a: 1, b: {
"$gt": 2}}}})
7.2 modulus ($mod)
For example, we need to match read % 5 == 1:
db.article.find({
"read": {
$mod: [5, 1]}})
7.3 Whether there is ($exists)
If we want to judge love Whether the field exists , It can be like this :
# If there are fields love, Just go back to
db.article.find({
"love": {
"$exists": true}})
# We can also judge that it doesn't exist , If there are no fields love, Just go back to
db.article.find({
"love": {
"$exists": false}})
7.4 Regular expressions
mongodb regular expression , The usage is the same as regular literal quantity :
# i Ignore case
db.article.find({
"title": /mongodb/i})
7.5 Types of queries
We can return data according to the field type :
# Only when comments The type of is array
db.article.find({
"comments": {
"$type": 4}})
7.6 Embedded documents
mongodb Is allowed to embed documents , And it's easy to query embedded documents ( Use point Syntax ):
{
address: {
name: "nanji" }
}
db.article.find({
"address.name": "nanji"})
Arrays can also take point Syntax :
{
comments: [{
title: "mongodb"}, {
title: "javascript"}]
}
db.article.find({
"comments.title": "mongodb"})
7.7 Take the opposite
$not It's a meta statement , It can be applied to any other condition :
db.article.find({
"author": {
"$not": /mongodb/i}})
Just use $not The operator , It means reverse .
7.8 Statistics
Returns the length of the matching data :
db.article.find().count()
7.9 format
pretty() Method to display all documents in a formatted way :
db.article.find().pretty()
️ If it works , Thank you for clicking three times !!!️
边栏推荐
- Arrangement of basic electrical knowledge (I)
- 一文告诉你什么是 Kubernetes
- 利用ELK 搭建日志分析系统(二)—— 部署安装
- 音频 scipy 中 spectrogram 的运作机制
- 等保2.0密码要求是什么?法律依据有哪些?
- 03 MongoDB文档的各种增加、更新、删除操作总结
- 多线程与高并发三:AQS底层源码分析及其实现类
- Talking about cloud primitiveness, we have to talk about containers
- How to apply for ASTM E108 flame retardant test for photovoltaic panels?
- 测不准原理
猜你喜欢

Meichuang data security management platform has obtained the evaluation certificate of "data security product capability verification plan" of the Institute

Pycharm不同项目之间共用第三方模块

欧洲家具EN 597-1 跟EN 597-2两个阻燃标准一样吗?

光伏板怎么申请ASTM E108阻燃测试?

Does the applet image component not display pictures?

电学基础知识整理(一)

机器学习入门笔记

How to apply for ASTM E108 flame retardant test for photovoltaic panels?

以自动化赋能转型,飞鹤乳业加速迈向数字化!

美创数据安全管理平台获信通院“数据安全产品能力验证计划”评测证书
随机推荐
小程序输入框闪动?
Detailed explanation of KVM common commands
谈云原生,不得不谈的容器
@Transactional失效的几种场景
2021年终总结及2022年展望
gcd最大公约数
开启创客教育造物学的领域
回溯—迷宫问题
《性能之巅第2版》阅读笔记(二)--性能观察工具
美创入选“2022 CCIA中国网络安全竞争力50强”榜单
Uncertainty principle
03 MongoDB文档的各种增加、更新、删除操作总结
How to apply for ASTM E108 flame retardant test for photovoltaic panels?
leetcode - 329. 矩阵中的最长递增路径
黑體輻射初探
Understanding and learning of parental delegation mechanism
基于正点原子stm32的mini板的TFTLCD显示实验
小程序的防抖节流怎么写?
English grammar_ Adjective / adverb Level 3 - Comparative
MSc 307 (88) (2010 FTPC code) Part 2 smoke and toxicity test