Home Database Mysql Tutorial mongoDB的Find详解、分页和排序、游标

mongoDB的Find详解、分页和排序、游标

Jun 07, 2016 pm 03:54 PM
find mongodb Pagination designation sort cursor Detailed explanation return

1.指定返回的键 db.[documentName].find ({条件},{键指定}) 数据准备persons.json var persons = [{ name:jim, age:25, email:75431457@qq.com, c:89,m:96,e:87, country:USA, books:[JS,C,EXTJS,MONGODB] }, { name:tom, age:25, email:214557457@qq.com, c

1.指定返回的键

db.[documentName].find ({条件},{键指定})

数据准备persons.json

var persons = [{
name:"jim",
age:25,
email:"75431457@qq.com",
c:89,m:96,e:87,
country:"USA",
books:["JS","C++","EXTJS","MONGODB"]
},
{
name:"tom",
age:25,
email:"214557457@qq.com",
c:75,m:66,e:97,
country:"USA",
books:["PHP","JAVA","EXTJS","C++"]
},
{
name:"lili",
age:26,
email:"344521457@qq.com",
c:75,m:63,e:97,
country:"USA",
books:["JS","JAVA","C#","MONGODB"]
},
{
name:"zhangsan",
age:27,
email:"2145567457@qq.com",
c:89,m:86,e:67,
country:"China",
books:["JS","JAVA","EXTJS","MONGODB"]
},
{
name:"lisi",
age:26,
email:"274521457@qq.com",
c:53,m:96,e:83,
country:"China",
books:["JS","C#","PHP","MONGODB"]
},
{
name:"wangwu",
age:27,
email:"65621457@qq.com",
c:45,m:65,e:99,
country:"China",
books:["JS","JAVA","C++","MONGODB"]
},
{
name:"zhaoliu",
age:27,
email:"214521457@qq.com",
c:99,m:96,e:97,
country:"China",
books:["JS","JAVA","EXTJS","PHP"]
},
{
name:"piaoyingjun",
age:26,
email:"piaoyingjun@uspcat.com",
c:39,m:54,e:53,
country:"Korea",
books:["JS","C#","EXTJS","MONGODB"]
},
{
name:"lizhenxian",
age:27,
email:"lizhenxian@uspcat.com",
c:35,m:56,e:47,
country:"Korea",
books:["JS","JAVA","EXTJS","MONGODB"]
},
{
name:"lixiaoli",
age:21,
email:"lixiaoli@uspcat.com",
c:36,m:86,e:32,
country:"Korea",
books:["JS","JAVA","PHP","MONGODB"]
},
{
name:"zhangsuying",
age:22,
email:"zhangsuying@uspcat.com",
c:45,m:63,e:77,
country:"Korea",
books:["JS","JAVA","C#","MONGODB"]
}]
for(var i = 0;i db.persons.insert(persons[i])
}

1.1 查询出所有数据的指定键(name ,age ,country)

db.persons.find({},{name:1,age:1,country:1,_id:0})

2.查询条件

\

2.查询条件

2.1查询出年龄在25到27岁之间的学生

db.persons.find({age: {$gte:25,$lte:27},{_id:0,age:1})

2.2查询出所有不是韩国籍的学生的数学成绩

db.persons.find({country:{$ne:”Korea”}},{_id:0,m:1})

3.包含或不包含

$in或$nin

2.3查询国籍是中国或美国的学生信息

db.persons.find({country:{$in:[“USA”,“China”]}})

2.4查询国籍不是中国或美国的学生信息

db.persons.find({country:{$nin:[“USA”,“China”]}})

4.OR查询

$or

2.4查询语文成绩大于85或者英语大于90的学生信息

db.persons.find({$or:[{c:{$gte:85}},{e:{$gte:90}}]},{_id:0,c:1,e:1})

5.Null

把中国国籍的学生上增加新的键sex

db.person.update({country:”China”},{$set:{sex:”m”}},false,true)

2.5查询出sex 等于 null的学生

db.persons.find({sex:{$in:[null]}},{country:1})

6.正则查询

2.6查询出名字中存在”li”的学生的信息

db.persons.find({name:/li/i},{_id:0,name:1})

7.$not的使用

$not可以用到任何地方进行取反操作

2.7查询出名字中不存在”li”的学生的信息

db.persons.find({name:{$not:/li/i}},{_id:0,name:1})

$not和$nin的区别是$not可以用在任何地方儿$nin是用到集合上的

8.数组查询$all和index应用

2.8查询喜欢看MONGOD和JS的学生

db.persons.find({books:{$all:[“MONGOBD”,”JS”]}},{books:1,_id:0})

2.9查询第二本书是JAVA的学习信息

db.persons.find({“books.1”:”JAVA”})

9.查询指定长度数组$size它不能与比较查询符一起使用(这是弊端)

2.8查询出喜欢的书籍数量是4本的学生

db.persons.find({books:{$size:4}},{_id:0,books:1})

2.9查询出喜欢的书籍数量大于3本的学生

1.增加字段size

db.persons.update({},{$set:{size:4}},false,true)

2.改变书籍的更新方式,每次增加书籍的时候size增加1

db.persons.update({查询器},{$push:{books:”ORACLE”},$inc:{size:1}})

3.利用$gt查询

db.persons.find({size:{$gt:3}})

2.10利用shell查询出Jim喜欢看的书的数量

var persons = db.persons.find({name:"jim"})

while(persons.hasNext()){

obj = persons.next();

print(obj.books.length)

}

课间小结

1.mongodb 是NOSQL数据库但是他在文档查询上还是很强大的

2.查询符基本是用到花括号里面的更新符基本是在外面

3.shell是个彻彻底底的JS引擎,但是一些特殊的操作要靠他的

各个驱动包来完成(JAVA,NODE.JS)

10.$slice操作符返回文档中指定数组的内部值

2.11查询出Jim书架中第2~4本书

db.persons.find({name:"jim"},{books:{"$slice":[1,3]}})

2.12查询出最后一本书

db.persons.find({name:"jim"},{books:{"$slice":-1},_id:0,name:1})

11.文档查询

为jim添加学习简历文档 jim.json

2.13查询出在K上过学的学生

1. 这个我们用绝对匹配可以完成,但是有些问题(找找问题?顺序?总要带着score?)

db.persons.find({school:{school:"K",score:"A"}},{_id:0,school:1})

2.为了解决顺序的问题我可以用对象”.”的方式定位

db.persons.find({"school.score":"A","school.school":"K"},{_id:0,school:1})

3.这样也问题看例子:

db.persons.find({"school.score":"A","school.school":”J”},{_id:0,school:1})

同样能查出刚才那条数据,原因是score和school会去其他对象对比

4.正确做法单条条件组查询$elemMatch

db.persons.find({school:{$elemMatch:{school:"K",score:"A"}}})

12.$where

12.查询年龄大于22岁,喜欢看C++书,在K学校上过学的学生信息

复杂的查询我们就可以用$where因为他是万能

但是我们要尽量避免少使用它因为他会有性能的代价

db.persons.find({"$where":function(){

var books = this.books;

var school = this.school;

if(this.age > 22){
var php = null;

for ( var i = 0; i if(books[i] == "C++"){
php = books[i];

if(school){
for (var j = 0; j
if(school[j].school == "K"){

return true;
}
}
break;
}
}
}
}
}})

二、分页和排序

1.Limit返回指定的数据条数

1.1查询出persons文档中前5条数据

db.persons.find({},{_id:0,name:1}).limit(5)

2.Skip返回指定数据的跨度

2.1查询出persons文档中5~10条的数据

db.persons.find({},{_id:0,name:1}).limit(5).skip(5)

3.Sort返回按照年龄排序的数据[1,-1]

db.persons.find({},{_id:0,name:1,age:1}).sort({age:1})

注意:mongodb的key可以存不同类型的数据排序就也有优先级

最小值

null

数字

字符串

对象/文档

数组

二进制

对象ID

布尔

日期

时间戳à正则 à最大值

4.Limit和Skip完成分页

4.1三条数据位一页进行分页

第一页àdb.persons.find({},{_id:0,name:1}).limit(3).skip(0)

第二页àdb.persons.find({},{_id:0,name:1}).limit(3).skip(3)

4.2skip有性能问题,没有特殊情况下我们也可以换个思路

对文档进行重新解构设计

\

每次查询操作的时候前后台传值全要把上次的最后一个文档的日期保存下来

db.persons.find({date:{$gt:日期数值}}).limit(3)

个人建议à应该把软件的中点放到便捷和精确查询上而不是分页的性能上

因为用户最多不会翻查过2页的

三、游标

利用游标遍历查询数据

var persons = db.persons.find();

while(persons.hasNext()){

obj = persons.next();

print(obj.name)

}

\

2.游标几个销毁条件

1.客户端发来信息叫他销毁

2.游标迭代完毕

3.默认游标超过10分钟没用也会别清除

3.查询快照

快照后就会针对不变的集合进行游标运动了,看看使用方法.

db.persons.find({$query:{name:”Jim”},$snapshot:true})

高级查询选项

$query

$orderby

$maxsan:integer最多扫描的文档数

$min:doc 查询开始

$max:doc 查询结束

$hint:doc 使用哪个索引

$explain:boolean 统计

$snapshot:boolean一致快照

\

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

How to choose a database for GitLab on CentOS How to choose a database for GitLab on CentOS Apr 14, 2025 pm 04:48 PM

GitLab Database Deployment Guide on CentOS System Selecting the right database is a key step in successfully deploying GitLab. GitLab is compatible with a variety of databases, including MySQL, PostgreSQL, and MongoDB. This article will explain in detail how to select and configure these databases. Database selection recommendation MySQL: a widely used relational database management system (RDBMS), with stable performance and suitable for most GitLab deployment scenarios. PostgreSQL: Powerful open source RDBMS, supports complex queries and advanced features, suitable for handling large data sets. MongoDB: Popular NoSQL database, good at handling sea

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

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

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.

MongoDB and relational database: a comprehensive comparison MongoDB and relational database: a comprehensive comparison Apr 08, 2025 pm 06:30 PM

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

How to set up users in mongodb How to set up users in mongodb Apr 12, 2025 am 08:51 AM

To set up a MongoDB user, follow these steps: 1. Connect to the server and create an administrator user. 2. Create a database to grant users access. 3. Use the createUser command to create a user and specify their role and database access rights. 4. Use the getUsers command to check the created user. 5. Optionally set other permissions or grant users permissions to a specific collection.

How to encrypt data in Debian MongoDB How to encrypt data in Debian MongoDB Apr 12, 2025 pm 08:03 PM

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

MongoDB vs. Oracle: Choosing the Right Database for Your Needs MongoDB vs. Oracle: Choosing the Right Database for Your Needs Apr 22, 2025 am 12:10 AM

MongoDB is suitable for unstructured data and high scalability requirements, while Oracle is suitable for scenarios that require strict data consistency. 1.MongoDB flexibly stores data in different structures, suitable for social media and the Internet of Things. 2. Oracle structured data model ensures data integrity and is suitable for financial transactions. 3.MongoDB scales horizontally through shards, and Oracle scales vertically through RAC. 4.MongoDB has low maintenance costs, while Oracle has high maintenance costs but is fully supported.

See all articles