Table of Contents
查询操作
基本查询
查询指定集合中的所有记录
相等条件查询
使用查询操作符声明多个条件
and条件查询
or条件查询
and or 混合查询
嵌入型记录查询
测试数据
精确匹配内嵌记录的某字段
匹配某些内嵌字段
数组
概述
精确匹配数组
查询结果需要精确匹配数组中的每个值,包括每个元素的顺序
匹配数组中的一个值
匹配数组指定位置的值
数组的多条件查询
单元素条件查询
多元素联合匹配查询
嵌入型记录数组
使用数组下标匹配嵌入型记录的某个字段
无需数组下标匹配字段
组合满足条件查询
Home Database Mysql Tutorial MongoDB操作手册CRUD查询

MongoDB操作手册CRUD查询

Jun 07, 2016 pm 04:05 PM
crud mongodb Basic operate Inquire

查询操作 基本查询 查询指定集合中的所有记录 db.testData.find()或者db.testData.find({}); 相等条件查询 db.testData.find({num:5});//查询num=5的记录 使用查询操作符声明多个条件 db.testData.find({num:{$in:[2,3,4]}});查询num为2,3,4的记录。 尽管可

查询操作

基本查询

查询指定集合中的所有记录

db.testData.find()或者db.testData.find({});

相等条件查询

db.testData.find({num:5});//查询num=5的记录

使用查询操作符声明多个条件

db.testData.find({num:{$in:[2,3,4]}});查询num为2,3,4的记录。
尽管可以使用$or操作符来执行同样的查询,但是当多个or条件都是在同一字段上的相等判断时,请使用$in而不是$or。

and条件查询

db.testData.find({name:'d',num:{$lt:10}});//查询name为d且num小于10的记录。lt = less than

or条件查询

db.find({$or:[{name:'a'},{num:{$gt:3}}])//查询name为a或者num大于3的记录。gt = greater than

and or 混合查询

db.testData.find({gender:'male',$or:[{name:'a'},{age:{$gt:3}}]});//查询gender为male,且(名字为a或者age>3)的记录。

嵌入型记录查询

当一个字段内嵌了一条记录,查询时既可以声明精确的(即字段顺序,字段值都匹配)去匹配内嵌记录某些字段,或者使用“.”来匹配内嵌记录的各个字段声明。

测试数据

db.testData.insert( { producer:{company:'a',address:'123'},name:'aaa' } );
db.testData.insert( { producer:{company:'a',address:'123'} } );

精确匹配内嵌记录的某字段

原来的db.testData.find(:)中,将改为匹配的内嵌记录即可
例:db.testData.find( { producer:{company:'a',address:'123'} } );
结果将返回以上两条测试数据
注意:
db.testData.find( { producer:{address:'123',company:'a'} } )
db.testData.find( { producer:{address:'123',name:'aaa'} } )
db.testData.find( { producer:{company:'a',name:'aaa'} } )
这三条语句都不会查询到结果,即这种查询方式必须从是从第一到第n个字段的匹配,字段顺序颠倒,或者不是挨着的都不会查到结果。

匹配某些内嵌字段

db.testData.find( { 'producer.company':'a' } );
db.testData.find( { 'producer.company':'a','producer.address':'123' } );
以上两条可以查询到所有测试数据。
注意:
db.testData.find( { 'producer.company':'a','producer.name':'aaa' } );
db.testData.find( { 'producer.address':'123','producer.name':'aaa' } );
db.testData.find( { 'producer.name':'aaa' } );
这三条语句也无法查询到测试数据,也就是说这种方式也必须是从第一到第n个字段的匹配,字段顺序,或者不是挨着的字段都不会查到结果

数组

概述

当某个字段保存数组,可以根据数组中的某个值来查询这条记录。如果这个数组保存着嵌入型记录,可以使用“.”查询。
如果使用$elemMatch声明多个条件来进行查询,数组必须至少包含一条记录满足所有条件。
如果没有使用$elemMatch来声明多个条件进行查询,那么满足条件的记录符合的条件是:这个数组中的各个元素能够覆盖条件的每个要求,如数组5,6,7,条件为=5且=7的情况下,数组中的5和7两个元素组合起来能够覆盖所有条件要求。

测试数据

db.testData.insert({ _id: 5, type: "food", item: "aaa", ratings: [ 5, 8, 9 ] });
db.testData.insert({ _id: 6, type: "food", item: "bbb", ratings: [ 5, 9 ] });
db.testData.insert({ _id: 7, type: "food", item: "ccc", ratings: [ 9, 5, 8 ] });

精确匹配数组

查询结果需要精确匹配数组中的每个值,包括每个元素的顺序

db.testData.find( { ratings: [ 5, 8, 9 ] } )

匹配数组中的一个值

db.testData.find( { ratings: 5 } )

匹配数组指定位置的值

db.testData.find( { 'ratings.0': 5 } )//匹配ratings数组中第一个元素为5的记录

数组的多条件查询

单元素条件查询
db.testData.find( { ratings: { $elemMatch: { $gt: 5, $lt: 9 } } } )//匹配ratings数组中至少有一个元素既大于5又小于9的记录。
多元素联合匹配查询
db.testData.find( { ratings: { $gt: 5, $lt: 9 } } )//匹配数组中有一个元素大于5,同时有另一个元素小于9的记录,或者某个元素同时满足这两个条件的记录。

嵌入型记录数组

测试数据

{
_id: 100,
type: "food",
item: "xyz",
qty: 25,
3.3. MongoDB CRUD Tutorials 91
MongoDB Documentation, Release 2.6.4
price: 2.5,
ratings: [ 5, 8, 9 ],
memos: [ { memo: "on time", by: "shipping" }, { memo: "approved", by: "billing" } ]
}
{
_id: 101,
type: "fruit",
item: "jkl",
qty: 10,
price: 4.25,
ratings: [ 5, 9 ],
memos: [ { memo: "on time", by: "payment" }, { memo: "delayed", by: "shipping" } ]
}

使用数组下标匹配嵌入型记录的某个字段

如果你知道嵌入型记录的数组顺序,可以用以下查询
db.testData.find( { 'memos.0.by': 'shipping' } )//匹配memos数组中第一元素的by字段为shipping的记录

无需数组下标匹配字段

不知道数组顺序的情况下,用以下查询
db.testData.find( { 'memos.by': 'shipping' } )//匹配memos数组中某个元素包含by字段且值为shipping的记录

数组的多条件查询

和数组查询一样,使用$elemMatch就是要数组中的某个元素满足所有条件,不用的话就是多个元素组合起来满足所有条件

单元素条件查询

使用$elemMatch来查询数组中某个元素满足所有的记录
db.testData.find(
{
memos:
{
$elemMatch:
{
memo: 'on time',
by: 'shipping'
}
}
}
)//匹配memos中某个元素既有memo为'on time'又有by为 'shipping'的记录

组合满足条件查询

db.inventory.find(
{
'memos.memo': 'on time',
'memos.by': 'shipping'
}
)//匹配memos数组中某个元素包含memo字段且值为on time,同时另一个元素包含by字段且值为shipping的记录,或者某个元素同时满足两条记录
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

Video Face Swap

Video Face Swap

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

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)

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

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.

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

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

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

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

Major update of Pi Coin: Pi Bank is coming! Major update of Pi Coin: Pi Bank is coming! Mar 03, 2025 pm 06:18 PM

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

See all articles