Home Database Mysql Tutorial MongoDB查询语法

MongoDB查询语法

Jun 07, 2016 pm 05:37 PM
mongodb Inquire grammar

mongoDb是非关系型数据库,用习惯了mssql,mysql等数据库的需要转换一下思维 mongoDb存的是与js的json结构一样的文档,表中的每一条记录都可以结构不同 1,大于,小于,大于等于,小于等于 $gt 大于 $lt 小于 $gte 大于或等于 = $lte 小于等于 = 示例 db.coll

mongoDb是非关系型数据库,用习惯了mssql,mysql等数据库的需要转换一下思维

mongoDb存的是与js的json结构一样的文档,表中的每一条记录都可以结构不同

 

1,大于,小于,大于等于,小于等于

$gt 大于   >

$lt 小于    

$gte 大于或等于  >=

$lte  小于等于    

示例

db.collection.find({age:{$gt:18}});  //年龄大于18岁,不包含18岁

SQL:SELECT * FROM Collection WHERE age>18

 

db.collection.find({age:{$lt:25}});  //年龄小于25岁,不包含25岁

SQL:SELECT * FROM Collection WHERE age

 

db.collection.find({age:{$gte:18}});//年龄大于等于18岁的,包含18岁

SQL:SELECT * FROM Collection WHERE age >=18

 

db.collection.find({age:{$lte:25}});//年龄小于等于25岁的,包含25岁

SQL:SELECT * FROM Collection WHERE age

 

也可以将两个条件合并,如下

db.collection.find({age:{$gt:18,$lt:25}}) ;//18

 

2,不等于

$ne 不等于 noe equals

db.collection.find({age:{$ne:18}})  ;//年龄不等于18

 

3,in,not in

$in,$nin


语法

db.collection.find({field:{$in:array}});

db.collection.find({field:{$nin:array}});

示例:

db.collection.find({id:{$in:[1,2,3,4]}})

db.collection.find({id:{$nin:[1,2,3,4]}});

 

4,$exists 验证一个元素是否存在

这个语法有点绕

db.collection.find({title:{$exists:true}});  //如果记录中有包含title属性的全部返回

db.collection.find({title:{$exists:false}}); //如果记录中有包含title属性的全部不返回,不包含title属性的全部返回

 

5,正则表达式

mongo支持正则表达式,,如:

db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写

支持正则表达式查询让mongDb具有相当强大的查询功能,不过同时需要开发者比较了解正则表达式

 

6  查询数据内的值

下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。db.things.find( { colors : "red" } );

7 $elemMatch

如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:

> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) 
{ "_id" : ObjectId("4b5783300334000000000aa9"), 
"x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
}$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。

注意,上面的语句和下面是不一样的。

> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } 

 

8  查询嵌入对象的值

db.postings.find( { "author.name" : "joe" } );

注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation

举个例子:

> db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})

如果我们要查询 authors name 是Jane的, 我们可以这样:

> db.blog.findOne({"author.name" : "Jane"})

如果不用点,那就需要用下面这句才能匹配:

db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})

下面这句:

db.blog.findOne({"author" : {"name" : "Jane"}})

是不能匹配的,因为mongodb对于子对象,他是精确匹配。

 

9 元操作符 $not 取反

如:

db.customers.find( { name : { $not : /acme.*corp/i } } );db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } ); 

 

以上是常用的查询语法,下一篇将介绍复合查询

最好的文档还是官方文档,英文好的可以自己看看

+operations+in+query+expressions

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What to do if navicat expires What to do if navicat expires Apr 23, 2024 pm 12:12 PM

Solutions to resolve Navicat expiration issues include: renew the license; uninstall and reinstall; disable automatic updates; use Navicat Premium Essentials free version; contact Navicat customer support.

What are the syntax and structure characteristics of lambda expressions? What are the syntax and structure characteristics of lambda expressions? Apr 25, 2024 pm 01:12 PM

Lambda expression is an anonymous function without a name, and its syntax is: (parameter_list)->expression. They feature anonymity, diversity, currying, and closure. In practical applications, Lambda expressions can be used to define functions concisely, such as the summation function sum_lambda=lambdax,y:x+y, and apply the map() function to the list to perform the summation operation.

How to connect navicat to mongodb How to connect navicat to mongodb Apr 24, 2024 am 11:27 AM

To connect to MongoDB using Navicat, you need to: Install Navicat Create a MongoDB connection: a. Enter the connection name, host address and port b. Enter the authentication information (if required) Add an SSL certificate (if required) Verify the connection Save the connection

What is the use of net4.0 What is the use of net4.0 May 10, 2024 am 01:09 AM

.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.

How nodejs implements database How nodejs implements database Apr 21, 2024 am 05:42 AM

Connecting to a database in Node.js requires choosing a database system (relational or non-relational) and then establishing a connection using modules specific to that type. Common modules include mysql (MySQL), pg (PostgreSQL), mongodb (MongoDB), and redis (Redis). After the connection is established, you can use query statements to retrieve data and update statements to modify the data. Finally, the connection must be closed when all operations are completed to release resources. Improve performance and security by following these best practices, such as using connection pooling, parameterized queries, and handling errors gracefully.

Integration of Java functions and databases in serverless architecture Integration of Java functions and databases in serverless architecture Apr 28, 2024 am 08:57 AM

In a serverless architecture, Java functions can be integrated with the database to access and manipulate data in the database. Key steps include: creating Java functions, configuring environment variables, deploying functions, and testing functions. By following these steps, developers can build complex applications that seamlessly access data stored in databases.

How to ensure high availability of MongoDB on Debian How to ensure high availability of MongoDB on Debian Apr 02, 2025 am 07:21 AM

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

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

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

See all articles