How To Get Collection Data In Mongodb
-
db.collection.find(query, projection)
-
mongosh Method
This is a
mongosh
method. This is not the documentation forNode.js
or other programming language specific driver methods.In most cases,
mongosh
methods work the same way as the legacymongo
trounce methods. However, some legacy methods are unavailable inmongosh
.For the legacy
mongo
shell documentation, refer to the documentation for the corresponding MongoDB Server release:- mongo trounce v4.iv
- mongo shell v4.two
- mongo shell v4.0
For MongoDB API drivers, refer to the linguistic communication specific MongoDB driver documentation.
Selects documents in a collection or view and returns a cursor to the selected documents.
Parameter
Type
Description
query
document
Optional. Specifies selection filter using query operators. To return all documents in a collection, omit this parameter or pass an empty document (
{}
).projection
certificate
Optional. Specifies the fields to return in the documents that lucifer the query filter. To return all fields in the matching documents, omit this parameter. For details, come across Projection.
Returns : A cursor to the documents that friction match the query
criteria. When thefind()
method "returns documents," the method is actually returning a cursor to the documents.
The projection
parameter determines which fields are returned in the matching documents. The projection
parameter takes a document of the post-obit form:
{ < field1 > : < value > , < field2 > : < value > ... }
Projection | Description |
---|---|
| Specifies the inclusion of a field. Not-nada integers are also treated every bit |
| Specifies the exclusion of a field. |
| With the use of the |
| Using the array projection operators |
| Using the |
| Specifies the value of the projected field. Starting in MongoDB 4.4, with the use of aggregation expressions and syntax, including the use of literals and aggregation variables, you can projection new fields or project existing fields with new values. For case, If y'all specify a non-numeric, not-boolean literal (such every bit a literal cord or an array or an operator expression) for the projection value, the field is projected with the new value; e.g.: To project a literal value for a field, use the In versions 4.2 and earlier, any specification value (with the exception of the previously unsupported document value) is treated equally either New in version 4.4. |
For fields in an embedded documents, yous can specify the field using either:
- dot notation; east.thou.
"field.nestedfield": <value>
- nested grade; e.k.
{ field: { nestedfield: <value> } }
(Starting in MongoDB 4.4)
The _id
field is included in the returned documents by default unless you explicitly specify _id: 0
in the projection to suppress the field.
A projection
cannot incorporate both include and exclude specifications, with the exception of the _id
field:
- In projections that explicitly include fields, the
_id
field is the only field that you tin explicitly exclude. - In projections that explicitly excludes fields, the
_id
field is the just field that you tin can explicitly include; still, the_id
field is included by default.
Run across Projection Examples.
Executing db.drove.notice()
in mongosh
automatically iterates the cursor to brandish up to the start twenty documents. Type information technology
to continue iteration.
To admission the returned documents with a commuter, utilize the advisable cursor handling mechanism for the driver language.
To specify the read concern for db.collection.find()
, use the cursor.readConcern()
method.
MongoDB treats some information types as equivalent for comparing purposes. For instance, numeric types undergo conversion before comparison. For almost data types, however, comparing operators only perform comparisons on documents where the BSON type of the target field matches the type of the query operand. Consider the following collection:
{ "_id": "apples", "qty": 5 } { "_id": "bananas", "qty": seven } { "_id": "oranges", "qty": { "in stock": eight, "ordered": 12 } } { "_id": "avocados", "qty": "fourteen" }
The post-obit query uses $gt
to return documents where the value of qty
is greater than four
.
db.drove.find( { qty: { $gt: 4 } } )
The query returns the following documents:
{ "_id": "apples", "qty": 5 } { "_id": "bananas", "qty": vii }
The certificate with _id
equal to "avocados"
is not returned because its qty
value is of type string
while the $gt
operand is of type integer
.
The document with _id
equal to "oranges"
is not returned considering its qty
value is of type object
.
New in version 4.0.
For cursors created inside a session, you cannot call getMore
outside the session.
Similarly, for cursors created outside of a session, you lot cannot call getMore
inside a session.
Starting in MongoDB 3.six, MongoDB drivers and mongosh
acquaintance all operations with a server session, with the exception of unacknowledged write operations. For operations not explicitly associated with a session (i.eastward. using Mongo.startSession()
), MongoDB drivers and mongosh
create an implicit session and associate it with the operation.
If a session is idle for longer than 30 minutes, the MongoDB server marks that session as expired and may close information technology at whatever time. When the MongoDB server closes the session, it also kills any in-progress operations and open cursors associated with the session. This includes cursors configured with noCursorTimeout()
or a maxTimeMS()
greater than 30 minutes.
For operations that may be idle for longer than thirty minutes, associate the operation with an explicit session using Mongo.startSession()
and periodically refresh the session using the refreshSessions
control. Come across Session Idle Timeout for more information.
db.collection.observe()
tin can exist used inside multi-document transactions.
- For cursors created exterior of a transaction, y'all cannot telephone call
getMore
within the transaction. - For cursors created in a transaction, yous cannot phone call
getMore
outside the transaction.
In about cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-certificate transactions should non be a replacement for effective schema pattern. For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your information and apply cases. That is, for many scenarios, modeling your information appropriately volition minimize the need for multi-certificate transactions.
For additional transactions usage considerations (such as runtime limit and oplog size limit), come across also Production Considerations.
Starting in MongoDB iv.2, if the client that issued db.collection.notice()
disconnects before the operation completes, MongoDB marks db.collection.observe()
for termination using killOp
.
The examples in this department use documents from the bios drove where the documents generally have the form:
{ "_id" : < value > , "name" : { "first" : < string > , "concluding" : < string > } , // embedded document "birth" : <ISODate> , "decease" : <ISODate> , "contribs" : [ < string > , ... ] , // Array of Strings "awards" : [ { "award" : < cord > , year: < number > , by: < cord > } // Array of embedded documents ... ] }
To create and populate the bios
collection, see The bios
Example Collection.
The observe()
method with no parameters returns all documents from a collection and returns all fields for the documents. For example, the following functioning returns all documents in the bios collection:
-
The following operation returns documents in the bios collection where
_id
equalsv
:db.bios.find( { _id: 5 } ) -
The following operation returns documents in the bios drove where the field
last
in thename
embedded document equals"Hopper"
:db.bios.find( { "name.concluding": "Hopper" } )To admission fields in an embedded document, employ dot notation (
"<embedded document>.<field>"
).
To detect documents that lucifer a set of selection criteria, call notice()
with the <criteria>
parameter.
MongoDB provides various query operators to specify the criteria.
-
The following operation uses the
$in
operator to render documents in the bios drove where_id
equals either5
orObjectId("507c35dd8fada716c89d0013")
:db.bios.find( { _id: { $in: [ five, ObjectId("507c35dd8fada716c89d0013") ] } } ) -
The following operation uses the
$gt
operator returns all the documents from thebios
drove wherenascence
is greater thannew Date('1950-01-01')
:db.bios.find( { birth: { $gt: new Appointment('1950-01-01') } } ) -
The post-obit operation uses the
$regex
operator to render documents in the bios collection wherename.terminal
field starts with the letterNorthward
(or is"LIKE N%"
)db.bios.detect( { "proper name.concluding": { $regex: /^North/ } } )
For a list of the query operators, run across Query Selectors.
Combine comparison operators to specify ranges for a field. The following operation returns from the bios collection documents where birth
is between new Appointment('1940-01-01')
and new Date('1960-01-01')
(exclusive):
db.bios.find( { nativity: { $gt: new Date('1940-01-01') , $lt: new Appointment('1960-01-01') } } )
For a listing of the query operators, run across Query Selectors.
The post-obit operation returns all the documents from the bios collection where birth
field is greater than
new Appointment('1950-01-01')
and expiry
field does non exists:
db.bios.find( { nativity: { $gt: new Date('1920-01-01') } , death: { $exists: simulated } } )
For a listing of the query operators, come across Query Selectors.
The following examples query the name
embedded field in the bios collection.
The following performance returns documents in the bios collection where the embedded certificate name
is exactly { starting time: "Yukihiro", last: "Matsumoto" }
, including the social club:
db.bios.notice( { name: { first: "Yukihiro", last: "Matsumoto" } } )
The name
field must lucifer the embedded document exactly. The query does not match documents with the following name
fields:
{ first: "Yukihiro", aka: "Matz", terminal: "Matsumoto" } { last: "Matsumoto", first: "Yukihiro" }
The following performance returns documents in the bios collection where the embedded document proper noun
contains a field kickoff
with the value "Yukihiro"
and a field last
with the value "Matsumoto"
. The query uses dot notation to admission fields in an embedded document:
db.bios.find( { "name.first": "Yukihiro", "name.concluding": "Matsumoto" } )
The query matches the document where the name
field contains an embedded document with the field first
with the value "Yukihiro"
and a field final
with the value "Matsumoto"
. For instance, the query would match documents with name
fields that held either of the following values:
{ first: "Yukihiro", aka: "Matz", last: "Matsumoto" } { terminal: "Matsumoto", first: "Yukihiro" }
For more than information and examples, run across likewise Query on Embedded/Nested Documents.
The following examples query the contribs
array in the bios collection.
-
The following performance returns documents in the bios collection where the array field
contribs
contains the element"UNIX"
:db.bios.find( { contribs: "UNIX" } ) -
The post-obit operation returns documents in the bios collection where the assortment field
contribs
contains the element"ALGOL"
or"Lisp"
:db.bios.detect( { contribs: { $in: [ "ALGOL", "Lisp" ]} } ) -
The following operation apply the
$all
query operator to render documents in the bios collection where the assortment fieldcontribs
contains both the elements"ALGOL"
and"Lisp"
:db.bios.find( { contribs: { $all: [ "ALGOL", "Lisp" ] } } )For more examples, see
$all
. Run across also$elemMatch
. -
The post-obit performance uses the
$size
operator to return documents in the bios collection where the assortment size ofcontribs
is iv:db.bios.detect( { contribs: { $size: 4 } } )
For more data and examples of querying an assortment, meet:
- Query an Assortment
- Query an Array of Embedded Documents
For a list of array specific query operators, see Array.
The following examples query the awards
array in the bios collection.
-
The following operation returns documents in the bios collection where the
awards
array contains an chemical element withlaurels
field equals"Turing Award"
:db.bios.find( { "awards.award": "Turing Award" } ) -
The following operation returns documents in the bios collection where the
awards
array contains at least i element with both theaward
field equals"Turing Award"
and theyear
field greater than 1980:db.bios.find( { awards: { $elemMatch: { award: "Turing Award", twelvemonth: { $gt: 1980 } } } } ) Use the
$elemMatch
operator to specify multiple criteria on an array element.
For more information and examples of querying an array, meet:
- Query an Array
- Query an Array of Embedded Documents
For a list of array specific query operators, run across Array.
The projection parameter specifies which fields to return. The parameter contains either include or exclude specifications, non both, unless the exclude is for the _id
field.
Unless the _id
field is explicitly excluded in the projection document _id: 0
, the _id
field is returned.
The following operation finds all documents in the bios collection and returns simply the proper noun
field, contribs
field and _id
field:
db.bios.find( { } , { proper noun: one, contribs: i } )
Unless the _id
field is explicitly excluded in the projection document _id: 0
, the _id
field is returned.
The following operation queries the bios collection and returns all fields except the first
field in the name
embedded document and the birth
field:
db.bios.observe( { contribs: 'OOP' } , { 'name.beginning': 0, birth: 0 } )
Unless the _id
field is explicitly excluded in the projection document _id: 0
, the _id
field is returned.
The following operation finds documents in the bios collection and returns simply the name
field and the contribs
field:
db.bios.find( { } , { name: 1, contribs: ane, _id: 0 } )
The post-obit operation queries the bios collection and returns the final
field in the proper name
embedded document and the kickoff ii elements in the contribs
assortment:
db.bios.notice( { } , { _id: 0, 'proper name.last': 1, contribs: { $slice: ii } } )
Starting in MongoDB iv.4, you lot can also specify embedded fields using the nested form, e.grand.
db.bios.find( { } , { _id: 0, name: { last: 1 } , contribs: { $slice: two } } )
Starting in MongoDB 4.4, db.collection.find()
projection can take aggregation expressions and syntax.
With the utilise of assemblage expressions and syntax, yous can project new fields or project existing fields with new values. For example, the following performance uses aggregation expressions to override the value of the name
and awards
fields likewise as to include new fields reportDate
, reportBy
, and reportNumber
.
db.bios.find( { } , { _id: 0, name: { $concat: [ { $ifNull: [ "$name.aka", "$name.outset" ] } , " ", "$proper name.last" ] } , birth: 1, contribs: 1, awards: { $cond: { if: { $isArray: "$awards" } , and then: { $size: "$awards" } , else: 0 } } , reportDate: { $dateToString: { date: new Engagement( ) , format: "%Y-%m-%d" } } , reportBy: "hellouser123", reportNumber: { $literal: 1 } } )
To set the reportRun
field to the value ane
The operation returns the post-obit documents:
{ "birth" : ISODate("1924-12-03T05:00:00Z") , "contribs" : [ "Fortran", "ALGOL", "Backus-Naur Course", "FP" ] , "proper name" : "John Backus", "awards" : 4, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 } { "birth" : ISODate("1927-09-04T04:00:00Z") , "contribs" : [ "Lisp", "Artificial Intelligence", "ALGOL" ] , "name" : "John McCarthy", "awards" : 3, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : ane } { "birth" : ISODate("1906-12-09T05:00:00Z") , "contribs" : [ "UNIVAC", "compiler", "FLOW-MATIC", "COBOL" ] , "proper name" : "Grace Hopper", "awards" : 4, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : one } { "birth" : ISODate("1926-08-27T04:00:00Z") , "contribs" : [ "OOP", "Simula" ] , "proper name" : "Kristen Nygaard", "awards" : 3, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 } { "birth" : ISODate("1931-x-12T04:00:00Z") , "contribs" : [ "OOP", "Simula" ] , "name" : "Ole-Johan Dahl", "awards" : three, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 } { "birth" : ISODate("1956-01-31T05:00:00Z") , "contribs" : [ "Python" ] , "proper name" : "Guido van Rossum", "awards" : two, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : one } { "birth" : ISODate("1941-09-09T04:00:00Z") , "contribs" : [ "UNIX", "C" ] , "name" : "Dennis Ritchie", "awards" : 3, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 } { "birth" : ISODate("1965-04-14T04:00:00Z") , "contribs" : [ "Ruby" ] , "name" : "Matz Matsumoto", "awards" : 1, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 } { "nascency" : ISODate("1955-05-19T04:00:00Z") , "contribs" : [ "Java" ] , "proper noun" : "James Gosling", "awards" : 2, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : i } { "contribs" : [ "Scala" ] , "name" : "Martin Odersky", "awards" : 0, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
The find()
method returns a cursor to the results.
In mongosh
, if the returned cursor is not assigned to a variable using the var
keyword, the cursor is automatically iterated to access up to the first 20 documents that match the query. Yous can set the DBQuery.shellBatchSize
variable to change the number of automatically iterated documents.
To manually iterate over the results, assign the returned cursor to a variable with the var
keyword, as shown in the post-obit sections.
The following example uses the variable myCursor
to iterate over the cursor and print the matching documents:
var myCursor = db.bios.observe( ) ; myCursor
The post-obit instance uses the cursor method side by side()
to admission the documents:
var myCursor = db.bios.notice( ) ; var myDocument = myCursor.hasNext( ) ? myCursor.next( ) : cipher; if ( myDocument) { var myName = myDocument.name; print (tojson( myName)) ; }
To print, you can also use the printjson()
method instead of print(tojson())
:
if ( myDocument) { var myName = myDocument.name; printjson( myName) ; }
The following instance uses the cursor method forEach()
to iterate the cursor and access the documents:
var myCursor = db.bios.find( ) ; myCursor.forEach( printjson) ;
mongosh
and the drivers provide several cursor methods that call on the cursor returned by the find()
method to alter its behavior.
The sort()
method orders the documents in the result set. The post-obit operation returns documents in the bios drove sorted in ascending society by the proper name
field:
db.bios.find( ).sort( { name: 1 } )
sort()
corresponds to the ORDER BY
statement in SQL.
The limit()
method limits the number of documents in the effect set up. The following operation returns at most 5
documents in the bios collection:
db.bios.discover( ).limit( 5 )
limit()
corresponds to the LIMIT
statement in SQL.
The skip()
method controls the starting point of the results set. The following operation skips the first 5
documents in the bios collection and returns all remaining documents:
Collation allows users to specify language-specific rules for string comparing, such as rules for lettercase and emphasis marks.
The collation()
method specifies the collation for the db.drove.find()
operation.
db.bios.observe( { "proper noun.last": "hopper" } ).collation( { locale: "en_US", strength: ane } )
The following statements chain cursor methods limit()
and sort()
:
db.bios.find( ).sort( { name: 1 } ).limit( 5 ) db.bios.find( ).limit( 5 ).sort( { name: 1 } )
The 2 statements are equivalent; i.e. the lodge in which you concatenation the limit()
and the sort()
methods is not significant. Both statements render the first five documents, as determined by the ascending sort order on 'proper name'.
|
|
How To Get Collection Data In Mongodb,
Source: https://www.mongodb.com/docs/manual/reference/method/db.collection.find/
Posted by: stephensexameste1969.blogspot.com
0 Response to "How To Get Collection Data In Mongodb"
Post a Comment