当前位置:网站首页>Mongodb tutorial Chapter 07 crud search document
Mongodb tutorial Chapter 07 crud search document
2022-07-21 18:05:00 【Teacher Tony who doesn't cut his hair】
This article will introduce how to use the findOne() and find() Method to find the document .
Use findOne() Method to find a single document
findOne() Method is used to return a single document in the collection that meets the condition , The syntax of this method is as follows :
db.collection.findOne(query, projection)
findOne() Method contains two optional parameters :
- query Used to specify a selection criterion ;
- projection Used to specify the returned field .
If omitted query Parameters ,findOne() Return to the first document stored on disk . If omitted projection Parameters , By default, all fields in the document are returned .
If you want to specify whether to return a field , You can specify projection Parameters :
{
field1: value, field1: value, ... }
among ,value Set to true perhaps 1 Indicates that the field is returned ; If value Set to false perhaps 0,MongoDB This field will not be returned .
By default ,MongoDB Always returns _id Field . If you do not need to return this field , Can be in projection The parameter specifies _id: 0.
If there are multiple documents that meet the query conditions ,findOne() Only the first document found on the disk will be returned .
Next, let's look at some examples , First create a collection products:
db.products.insertMany([
{
"_id" : 1, "name" : "xPhone", "price" : 799, "releaseDate": ISODate("2011-05-14"), "spec" : {
"ram" : 4, "screen" : 6.5, "cpu" : 2.66 },"color":["white","black"],"storage":[64,128,256]},
{
"_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate": ISODate("2011-09-01") , "spec" : {
"ram" : 16, "screen" : 9.5, "cpu" : 3.66 },"color":["white","black","purple"],"storage":[128,256,512]},
{
"_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate": ISODate("2015-01-14"), "spec" : {
"ram" : 12, "screen" : 9.7, "cpu" : 3.66 },"color":["blue"],"storage":[16,64,128]},
{
"_id" : 4, "name" : "SmartPad", "price" : 699, "releaseDate": ISODate("2020-05-14"),"spec" : {
"ram" : 8, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256,1024]},
{
"_id" : 5, "name" : "SmartPhone", "price" : 599,"releaseDate": ISODate("2022-09-14"), "spec" : {
"ram" : 4, "screen" : 5.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256]}
])
The following example uses findOne() Method to find a collection products The first document in :
db.products.findOne()
The query returns all fields in the document :
{
_id: 1,
name: 'xPhone',
price: 799,
releaseDate: ISODate("2011-05-14T00:00:00.000Z"),
spec: {
ram: 4, screen: 6.5, cpu: 2.66 },
color: [ 'white', 'black' ],
storage: [ 64, 128, 256 ]
}
Omit query Parameter is the same as specifying an empty document parameter :
db.products.findOne({
})
The following sentence uses findOne() Method to find the _id be equal to 2 Documents :
db.products.findOne({
_id:2})
The results are as follows :
{
_id: 2,
name: 'xTablet',
price: 899,
releaseDate: ISODate("2011-09-01T00:00:00.000Z"),
spec: {
ram: 16, screen: 9.5, cpu: 3.66 },
color: [ 'white', 'black', 'purple' ],
storage: [ 128, 256, 512 ]
}
The following example uses findOne() Method to find the _id be equal to 5 Documents , And only returned _id and name Field :
db.products.findOne({
_id: 5}, {
name: 1})
{
"_id" : 5, "name" : "SmartPhone" }
As you can see from the returned results ,MongoDB By default _id Field .
If you want to remove from the returned result _id Field , You can specify _id:0, for example :
db.products.findOne({
_id: 5 }, {
name: 1, _id: 0})
{
"name" : "SmartPhone" }
Use find() Method to find the document
find() Method is used to find documents that meet specified conditions , And return a cursor pointing to these documents ( The pointer ). The syntax of this method is as follows :
db.collection.find(query, projection)
find() Method contains two optional parameters :
- query Used to specify a selection criterion . If you omit this parameter or specify an empty document parameter , All documents in the collection will be returned .
- projection Used to specify the returned field . If this parameter is omitted , All fields in the document will be returned .
By default ,MongoDB Always returns _id Field . If you do not need to return this field , Can be in projection The parameter specifies _id: 0.
because mongo shell Automatic traversal find() Method returns a cursor , We do not need to perform additional operations to get the document in the cursor . By default ,mongo shell Show only before 20 document , Input it Command can display more documents .
Now let's use a new set books As a demonstration :
db.books.insertMany([
{
"_id" : 1, "title" : "Unlocking Android", "isbn" : "1933988673", "categories" : [ "Open Source", "Mobile" ] },
{
"_id" : 2, "title" : "Android in Action, Second Edition", "isbn" : "1935182722", "categories" : [ "Java" ] },
{
"_id" : 3, "title" : "Specification by Example", "isbn" : "1617290084", "categories" : [ "Software Engineering" ] },
{
"_id" : 4, "title" : "Flex 3 in Action", "isbn" : "1933988746", "categories" : [ "Internet" ] },
{
"_id" : 5, "title" : "Flex 4 in Action", "isbn" : "1935182420", "categories" : [ "Internet" ] },
{
"_id" : 6, "title" : "Collective Intelligence in Action", "isbn" : "1933988312", "categories" : [ "Internet" ] },
{
"_id" : 7, "title" : "Zend Framework in Action", "isbn" : "1933988320", "categories" : [ "Web Development" ] },
{
"_id" : 8, "title" : "Flex on Java", "isbn" : "1933988797", "categories" : [ "Internet" ] },
{
"_id" : 9, "title" : "Griffon in Action", "isbn" : "1935182234", "categories" : [ "Java" ] },
{
"_id" : 10, "title" : "OSGi in Depth", "isbn" : "193518217X", "categories" : [ "Java" ] },
{
"_id" : 11, "title" : "Flexible Rails", "isbn" : "1933988509", "categories" : [ "Web Development" ] },
{
"_id" : 13, "title" : "Hello! Flex 4", "isbn" : "1933988762", "categories" : [ "Internet" ] },
{
"_id" : 14, "title" : "Coffeehouse", "isbn" : "1884777384", "categories" : [ "Miscellaneous" ] },
{
"_id" : 15, "title" : "Team Foundation Server 2008 in Action", "isbn" : "1933988592", "categories" : [ "Microsoft .NET" ] },
{
"_id" : 16, "title" : "Brownfield Application Development in .NET", "isbn" : "1933988711", "categories" : [ "Microsoft" ] },
{
"_id" : 17, "title" : "MongoDB in Action", "isbn" : "1935182870", "categories" : [ "Next Generation Databases" ] },
{
"_id" : 18, "title" : "Distributed Application Development with PowerBuilder 6.0", "isbn" : "1884777686", "categories" : [ "PowerBuilder" ] },
{
"_id" : 19, "title" : "Jaguar Development with PowerBuilder 7", "isbn" : "1884777864", "categories" : [ "PowerBuilder", "Client-Server" ] },
{
"_id" : 20, "title" : "Taming Jaguar", "isbn" : "1884777686", "categories" : [ "PowerBuilder" ] },
{
"_id" : 21, "title" : "3D User Interfaces with Java 3D", "isbn" : "1884777902", "categories" : [ "Java", "Computer Graphics" ] },
{
"_id" : 22, "title" : "Hibernate in Action", "isbn" : "193239415X", "categories" : [ "Java" ] },
{
"_id" : 23, "title" : "Hibernate in Action (Chinese Edition)", "categories" : [ "Java" ] },
{
"_id" : 24, "title" : "Java Persistence with Hibernate", "isbn" : "1932394885", "categories" : [ "Java" ] },
{
"_id" : 25, "title" : "JSTL in Action", "isbn" : "1930110529", "categories" : [ "Internet" ] },
{
"_id" : 26, "title" : "iBATIS in Action", "isbn" : "1932394826", "categories" : [ "Web Development" ] },
{
"_id" : 27, "title" : "Designing Hard Software", "isbn" : "133046192", "categories" : [ "Object-Oriented Programming", "S" ] },
{
"_id" : 28, "title" : "Hibernate Search in Action", "isbn" : "1933988649", "categories" : [ "Java" ] },
{
"_id" : 29, "title" : "jQuery in Action", "isbn" : "1933988355", "categories" : [ "Web Development" ] },
{
"_id" : 30, "title" : "jQuery in Action, Second Edition", "isbn" : "1935182323", "categories" : [ "Java" ] }
]);
The following example uses find() Method returns a collection books All documents in :
db.books.find()
mongo shell It shows the front 20 document , Contains all fields . Input it Command and return , You will see the following 20 document .
The following example returns _id be equal to 10 Documents , Contains all fields of the document :
db.books.find({
_id: 10})
[
{
_id: 10,
title: 'OSGi in Depth',
isbn: '193518217X',
categories: [ 'Java' ]
}
]
The following example returns category be equal to “Java” All documents of , The returned result contains _id、title as well as isbn Three fields :
db.books.find({
categories: 'Java'}, {
title: 1,isbn: 1})
[
{
_id: 2,
title: 'Android in Action, Second Edition',
isbn: '1935182722'
},
{
_id: 9, title: 'Griffon in Action', isbn: '1935182234' },
{
_id: 10, title: 'OSGi in Depth', isbn: '193518217X' },
{
_id: 21,
title: '3D User Interfaces with Java 3D',
isbn: '1884777902'
},
{
_id: 22, title: 'Hibernate in Action', isbn: '193239415X' },
{
_id: 23, title: 'Hibernate in Action (Chinese Edition)' },
{
_id: 24,
title: 'Java Persistence with Hibernate',
isbn: '1932394885'
},
{
_id: 28, title: 'Hibernate Search in Action', isbn: '1933988649' },
{
_id: 30,
title: 'jQuery in Action, Second Edition',
isbn: '1935182323'
}
]
Use the projection operation to return the specified field
stay MongoDB in , Projection (projection) Indicates that the specified field is returned in the query .
By default find() and findOne() Method will return all fields in the document , But in most cases, we don't need to query all the fields .
If you want to choose to return some fields , You can specify these fields in a document and pass the document as a parameter to find() and findOne() Method . This parameter document is called projection document . The syntax of specifying the return field is as follows :
{
<field>: value, ...}
If value Set to 1 perhaps true, Indicates the return field ; If value Set to 0 perhaps false, Indicates that this field is not returned . If the projection document is empty ({}), Indicates that all fields are returned .
For fields in embedded documents , You can use point numbers to specify :
{
"<embeddedDocument>.<field>": value, ... }
The following example returns _id be equal to 1 In the document name、price as well as _id Field , It also returns the embedded document spec Medium screen Field :
db.products.find({
_id:1}, {
name: 1,
price: 1,
"spec.screen": 1
})
The output is as follows :
[ {
_id: 1, name: 'xPhone', price: 799, spec: {
screen: 6.5 } } ]
MongoDB 4.4 And later versions also support specifying the returned fields in a nested form :
db.products.find({
_id:1}, {
name: 1,
price: 1,
spec : {
screen: 1 }
})
A similar , For fields in the array , You can also specify :
{
"<arrayField>.field": value, ...}
The following example returns _id、name And arrays inventory Medium qty Field :
db.products.find({
}, {
name: 1,
"inventory.qty": 1
});
The output is as follows :
[
{
_id: 1, name: 'xPhone', inventory: [ {
qty: 1200 } ] },
{
_id: 2, name: 'xTablet', inventory: [ {
qty: 300 } ] },
{
_id: 3, name: 'SmartTablet', inventory: [ {
qty: 400 }, {
qty: 200 } ]
},
{
_id: 4, name: 'SmartPad', inventory: [ {
qty: 1200 } ] },
{
_id: 5, name: 'SmartPhone' }
]
边栏推荐
猜你喜欢
随机推荐
From front-line development to technical director, you are almost on the shelf
ipset v7.10: Kernel error received: set type not supported
史上最全的mysql数据类型汇总(下)
Explain cache penetration, cache avalanche, cache breakdown
Simple understanding -- JVM
ASCII码与16进制转换表
Video 4413.8 regional convolutional neural network (r-cnn) series 13.5 multiscale target detection & 13.6 target detection data set
Bit operation of code
NUMA 的平衡和调度
聊聊伪共享
Prevent duplicate insert data in SQLite
Clickhouse-CPU内存资源优化配置
Understand RTK Positioning, this one is enough!
Overview and deployment of redis (master-slave replication, sentinel mode, cluster)
The difference between isnotblank() method and isnotempty() method
Redis practice (I) login
20220720 learning reflection
How to use sketch to design web pages and create grid guides tutorial
知识图谱赋能数字经济,第十六届全国知识图谱与语义计算大会(CCKS 2022)即将召开
STM32F103按键控制LED程序