diff --git a/source/applications/create.txt b/source/applications/create.txt index d2a165e5f8b..b686bee6411 100644 --- a/source/applications/create.txt +++ b/source/applications/create.txt @@ -11,17 +11,19 @@ operations and the factors that affect their performance, see :doc:`/core/write-operations`; for documentation of the other CRUD operations, see the :doc:`/crud` page. +.. contents:: + :backlinks: none + :local: + Overview -------- You can create documents in a MongoDB collection using any of the -following basic operations. +following basic operations: - :ref:`insert ` -- :ref:`create with save ` - -- :ref:`create with upsert ` +- :ref:`upsert ` All insert operations in MongoDB exhibit the following properties: @@ -45,10 +47,10 @@ All insert operations in MongoDB exhibit the following properties: .. _crud-create-insert: -Insert ------- +``insert()`` +------------ -The :method:`insert() ` is the primary method +The :method:`~db.collection.insert()` is the primary method to insert a document or documents into a MongoDB collection, and has the following syntax: @@ -58,301 +60,281 @@ the following syntax: .. admonition:: Corresponding Operation in SQL - The :method:`insert() ` method is analogous + The :method:`~db.collection.insert()` method is analogous to the ``INSERT`` statement. -Consider the following examples that illustrate the behavior of -:method:`insert() `: +Insert the First Document in a Collection +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- If the collection does not exist [#show-collection]_, then the - :method:`insert() ` method creates the - collection during the first insert. Specifically in the example, if - the collection ``bios`` does not exist , then the insert operation - will create this collection: +If the collection does not exist [#show-collection]_, then the +:method:`~db.collection.insert()` method creates the +collection during the first insert. Specifically in the example, if the +collection ``bios`` does not exist , then the insert operation will +create this collection: - .. code-block:: javascript - - db.bios.insert( - { - _id: 1, - name: { first: 'John', last: 'Backus' }, - birth: new Date('Dec 03, 1924'), - death: new Date('Mar 17, 2007'), - contribs: [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ], - awards: [ - { - award: 'W.W. McDowell Award', - year: 1967, - by: 'IEEE Computer Society' - }, - { - award: 'National Medal of Science', - year: 1975, - by: 'National Science Foundation' - }, - { - award: 'Turing Award', - year: 1977, - by: 'ACM' - }, - { - award: 'Draper Prize', - year: 1993, - by: 'National Academy of Engineering' - } - ] - } - ) +.. code-block:: javascript - You can confirm the insert by :doc:`querying ` - the ``bios`` collection: + db.bios.insert( + { + _id: 1, + name: { first: 'John', last: 'Backus' }, + birth: new Date('Dec 03, 1924'), + death: new Date('Mar 17, 2007'), + contribs: [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ], + awards: [ + { + award: 'W.W. McDowell Award', + year: 1967, + by: 'IEEE Computer Society' + }, + { + award: 'National Medal of Science', + year: 1975, + by: 'National Science Foundation' + }, + { + award: 'Turing Award', + year: 1977, + by: 'ACM' + }, + { + award: 'Draper Prize', + year: 1993, + by: 'National Academy of Engineering' + } + ] + } + ) + +You can confirm the insert by :doc:`querying ` +the ``bios`` collection: - .. code-block:: javascript +.. code-block:: javascript - db.bios.find() + db.bios.find() - This operation returns the following document from the ``bios`` - collection: +This operation returns the following document from the ``bios`` +collection: - .. code-block:: javascript +.. code-block:: javascript - { - "_id" : 1, - "name" : { "first" : "John", "last" : "Backus" }, - "birth" : ISODate("1924-12-03T05:00:00Z"), - "death" : ISODate("2007-03-17T04:00:00Z"), - "contribs" : [ "Fortran", "ALGOL", "Backus-Naur Form", "FP" ], - "awards" : [ - { - "award" : "W.W. McDowell Award", - "year" : 1967, - "by" : "IEEE Computer Society" - }, - { - "award" : "National Medal of Science", - "year" : 1975, - "by" : "National Science Foundation" - }, - { - "award" : "Turing Award", - "year" : 1977, - "by" : "ACM" - }, - { "award" : "Draper Prize", - "year" : 1993, - "by" : "National Academy of Engineering" - } - ] - } + { + "_id" : 1, + "name" : { "first" : "John", "last" : "Backus" }, + "birth" : ISODate("1924-12-03T05:00:00Z"), + "death" : ISODate("2007-03-17T04:00:00Z"), + "contribs" : [ "Fortran", "ALGOL", "Backus-Naur Form", "FP" ], + "awards" : [ + { + "award" : "W.W. McDowell Award", + "year" : 1967, + "by" : "IEEE Computer Society" + }, + { + "award" : "National Medal of Science", + "year" : 1975, + "by" : "National Science Foundation" + }, + { + "award" : "Turing Award", + "year" : 1977, + "by" : "ACM" + }, + { "award" : "Draper Prize", + "year" : 1993, + "by" : "National Academy of Engineering" + } + ] + } + +Insert a Document without Specifying an ``_id`` Field +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If the new document does not contain an ``_id`` field, then the +:method:`~db.collection.insert()` method adds the ``_id`` +field to the document and generates a unique ``ObjectId`` for the value: -- If the new document does not contain an ``_id`` field, then the - :method:`insert() ` method adds the ``_id`` - field to the document and generates a unique ``ObjectId`` for the value. +.. code-block:: javascript - .. code-block:: javascript + db.bios.insert( + { + name: { first: 'John', last: 'McCarthy' }, + birth: new Date('Sep 04, 1927'), + death: new Date('Dec 24, 2011'), + contribs: [ 'Lisp', 'Artificial Intelligence', 'ALGOL' ], + awards: [ + { + award: 'Turing Award', + year: 1971, + by: 'ACM' + }, + { + award: 'Kyoto Prize', + year: 1988, + by: 'Inamori Foundation' + }, + { + award: 'National Medal of Science', + year: 1990, + by: 'National Science Foundation' + } + ] + } + ) + +You can verify the inserted document by the querying the ``bios`` +collection: - db.bios.insert( - { - name: { first: 'John', last: 'McCarthy' }, - birth: new Date('Sep 04, 1927'), - death: new Date('Dec 24, 2011'), - contribs: [ 'Lisp', 'Artificial Intelligence', 'ALGOL' ], - awards: [ - { - award: 'Turing Award', - year: 1971, - by: 'ACM' - }, - { - award: 'Kyoto Prize', - year: 1988, - by: 'Inamori Foundation' - }, - { - award: 'National Medal of Science', - year: 1990, - by: 'National Science Foundation' - } - ] - } - ) +.. code-block:: javascript - You can verify the inserted document by the querying the ``bios`` - collection: + db.bios.find( { name: { first: 'John', last: 'McCarthy' } } ) - .. code-block:: javascript +The returned document contains an ``_id`` field with the generated +``ObjectId`` value: - db.bios.find( { name: { first: 'John', last: 'McCarthy' } } ) +.. code-block:: javascript - The returned document contains an ``_id`` field with the generated - ``ObjectId`` value: + { + "_id" : ObjectId("50a1880488d113a4ae94a94a"), + "name" : { "first" : "John", "last" : "McCarthy" }, + "birth" : ISODate("1927-09-04T04:00:00Z"), + "death" : ISODate("2011-12-24T05:00:00Z"), + "contribs" : [ "Lisp", "Artificial Intelligence", "ALGOL" ], + "awards" : [ + { + "award" : "Turing Award", + "year" : 1971, + "by" : "ACM" + }, + { + "award" : "Kyoto Prize", + "year" :1988, + "by" : "Inamori Foundation" + }, + { + "award" : "National Medal of Science", + "year" : 1990, + "by" : "National Science Foundation" + } + ] + } + +Bulk Insert Multiple Documents +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you pass an array of documents to the +:method:`~db.collection.insert()` method, the +:method:`~db.collection.insert()` performs a bulk insert into a +collection. + +The following operation inserts three documents into the ``bios`` +collection. The operation also illustrates the *dynamic schema* +characteristic of MongoDB. Although the document with ``_id: 3`` +contains a field ``title`` which does not appear in the other +documents, MongoDB does not require the other documents to contain this +field: - .. code-block:: javascript +.. code-block:: javascript - { - "_id" : ObjectId("50a1880488d113a4ae94a94a"), - "name" : { "first" : "John", "last" : "McCarthy" }, - "birth" : ISODate("1927-09-04T04:00:00Z"), - "death" : ISODate("2011-12-24T05:00:00Z"), - "contribs" : [ "Lisp", "Artificial Intelligence", "ALGOL" ], - "awards" : [ + db.bios.insert( + [ + { + _id: 3, + name: { first: 'Grace', last: 'Hopper' }, + title: 'Rear Admiral', + birth: new Date('Dec 09, 1906'), + death: new Date('Jan 01, 1992'), + contribs: [ 'UNIVAC', 'compiler', 'FLOW-MATIC', 'COBOL' ], + awards: [ + { + award: 'Computer Sciences Man of the Year', + year: 1969, + by: 'Data Processing Management Association' + }, { - "award" : "Turing Award", - "year" : 1971, - "by" : "ACM" + award: 'Distinguished Fellow', + year: 1973, + by: ' British Computer Society' }, { - "award" : "Kyoto Prize", - "year" :1988, - "by" : "Inamori Foundation" + award: 'W. W. McDowell Award', + year: 1976, + by: 'IEEE Computer Society' }, { - "award" : "National Medal of Science", - "year" : 1990, - "by" : "National Science Foundation" + award: 'National Medal of Technology', + year: 1991, + by: 'United States' } - ] - } - -- If you pass an array of documents to the :method:`insert() - ` method, the :method:`insert() - ` performs a bulk insert into a collection. - - The following operation inserts three documents into the - ``bios`` collection. The operation also illustrates the - *dynamic schema* characteristic of MongoDB. Although the document - with ``_id: 3`` contains a field ``title`` which does not appear in - the other documents, MongoDB does not require the other documents to - contain this field: - - .. code-block:: javascript - - db.bios.insert( - [ - { - _id: 3, - name: { first: 'Grace', last: 'Hopper' }, - title: 'Rear Admiral', - birth: new Date('Dec 09, 1906'), - death: new Date('Jan 01, 1992'), - contribs: [ 'UNIVAC', 'compiler', 'FLOW-MATIC', 'COBOL' ], - awards: [ - { - award: 'Computer Sciences Man of the Year', - year: 1969, - by: 'Data Processing Management Association' - }, - { - award: 'Distinguished Fellow', - year: 1973, - by: ' British Computer Society' - }, - { - award: 'W. W. McDowell Award', - year: 1976, - by: 'IEEE Computer Society' - }, - { - award: 'National Medal of Technology', - year: 1991, - by: 'United States' - } - ] - }, - { - _id: 4, - name: { first: 'Kristen', last: 'Nygaard' }, - birth: new Date('Aug 27, 1926'), - death: new Date('Aug 10, 2002'), - contribs: [ 'OOP', 'Simula' ], - awards: [ - { - award: 'Rosing Prize', - year: 1999, - by: 'Norwegian Data Association' - }, - { - award: 'Turing Award', - year: 2001, - by: 'ACM' - }, - { - award: 'IEEE John von Neumann Medal', - year: 2001, - by: 'IEEE' - } - ] - }, - { - _id: 5, - name: { first: 'Ole-Johan', last: 'Dahl' }, - birth: new Date('Oct 12, 1931'), - death: new Date('Jun 29, 2002'), - contribs: [ 'OOP', 'Simula' ], - awards: [ - { - award: 'Rosing Prize', - year: 1999, - by: 'Norwegian Data Association' - }, - { - award: 'Turing Award', - year: 2001, - by: 'ACM' - }, - { - award: 'IEEE John von Neumann Medal', - year: 2001, - by: 'IEEE' - } - ] - } - ] - ) - -.. [#show-collection] You can also view a list of the existing - collections in the database using the ``show collections`` - operation in the :program:`mongo` shell. - -.. _crud-create-save: - -Create with Save ----------------- + ] + }, + { + _id: 4, + name: { first: 'Kristen', last: 'Nygaard' }, + birth: new Date('Aug 27, 1926'), + death: new Date('Aug 10, 2002'), + contribs: [ 'OOP', 'Simula' ], + awards: [ + { + award: 'Rosing Prize', + year: 1999, + by: 'Norwegian Data Association' + }, + { + award: 'Turing Award', + year: 2001, + by: 'ACM' + }, + { + award: 'IEEE John von Neumann Medal', + year: 2001, + by: 'IEEE' + } + ] + }, + { + _id: 5, + name: { first: 'Ole-Johan', last: 'Dahl' }, + birth: new Date('Oct 12, 1931'), + death: new Date('Jun 29, 2002'), + contribs: [ 'OOP', 'Simula' ], + awards: [ + { + award: 'Rosing Prize', + year: 1999, + by: 'Norwegian Data Association' + }, + { + award: 'Turing Award', + year: 2001, + by: 'ACM' + }, + { + award: 'IEEE John von Neumann Medal', + year: 2001, + by: 'IEEE' + } + ] + } + ] + ) -The :method:`save() ` method is a specialized -upsert that use the ``_id`` field in the ```` argument to -determine whether to perform an insert or an update: +.. _crud-create-insert-save: -- If the ```` argument does not contain the ``_id`` field or - contains an ``_id`` field with a value not in the collection, the - :method:`save() ` method performs an insert of - the document. +Insert a Document with ``save()`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Otherwise, the :method:`save() ` method - performs an update. +The :method:`~db.collection.save()` method performs an insert +if the document to save does not contain the ``_id`` field. -The :method:`save() ` method has the -following syntax: +The following :method:`~db.collection.save()` operation performs an +insert into the ``bios`` collection since the document does not contain +the ``_id`` field: .. code-block:: javascript - db.collection.save( ) - -Consider the following examples that illustrate the use of the -:method:`save() ` method to perform inserts: - -- If the ```` does not contain the ``_id`` field, the - :method:`save() ` method performs an insert. - Refer to the :ref:`insert ` section for details - of the insert operation of a document without an ``_id`` field. - - The following operation performs an insert into the ``bios`` - collection since the document does not contain the ``_id`` field: - - .. code-block:: javascript - - db.bios.save( - { + db.bios.save( + { name: { first: 'Guido', last: 'van Rossum'}, birth: new Date('Jan 31, 1956'), contribs: [ 'Python' ], @@ -367,49 +349,26 @@ Consider the following examples that illustrate the use of the year: 2003, by: 'NLUUG' } - ] - } - ) + ] + } + ) -- If the ```` contains an ``_id`` field but has a value not - found in the collection, the :method:`save() ` - method performs an insert. Refer to the :ref:`insert - ` section for details of the insert operation. - - The following operation performs an insert into the ``bios`` - collection since the document contains an ``_id`` field whose value - ``10`` is not found in the ``bios`` collection: - - .. code-block:: javascript - - db.bios.save( - { - _id: 10, - name: { first: 'Yukihiro', aka: 'Matz', last: 'Matsumoto'}, - birth: new Date('Apr 14, 1965'), - contribs: [ 'Ruby' ], - awards: [ - { - award: 'Award for the Advancement of Free Software', - year: '2011', - by: 'Free Software Foundation' - } - ] - } - ) +.. [#show-collection] You can also view a list of the existing + collections in the database using the ``show collections`` + operation in the :program:`mongo` shell. .. _crud-create-update: -Create with Upsert ------------------- +Upserts (``update()``) +---------------------- An *upsert* eliminates the need to perform a separate database call to check for the existence of a record before performing either an update or an insert operation. Typically update operations :doc:`update ` existing documents, but in MongoDB, the -:method:`update() ` operation can accept an -```` option as an argument. Upserts are a hybrid operation that -use the ```` argument to determine the write operation: +:method:`~db.collection.update()` operation can accept an ```` +option as an argument. Upserts are a hybrid operation that use the +```` argument to determine the write operation: - If the query matches an existing document(s), the upsert performs an update. @@ -417,7 +376,7 @@ use the ```` argument to determine the write operation: - If the query matches no document in the collection, the upsert inserts a single document. -Consider the following syntax for an upsert operation: +An upsert operation has the following syntax: .. code-block:: javascript @@ -425,97 +384,132 @@ Consider the following syntax for an upsert operation: , { upsert: true } ) -The following examples illustrate the use of the upsert to perform -create operations: +Insert a Document that Contains ``field`` and ``value`` Pairs +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- If no document matches the ```` argument, the ``upsert`` - performs an insert. If the ```` argument includes only field - and value pairs, the new document contains the fields and values - specified in the ```` argument. If the ``_id`` field is - omitted, the operation adds the ``_id`` field and generates a unique - ``ObjectId`` for its value. +If no document matches the ```` argument, the ``upsert`` +performs an insert. If the ```` argument includes only field +and value pairs, the new document contains the fields and values +specified in the ```` argument. If the ``_id`` field is +omitted, the operation adds the ``_id`` field and generates a unique +``ObjectId`` for its value. - The following ``upsert`` operation inserts a new document into the - ``bios`` collection: +The following ``upsert`` operation inserts a new document into the +``bios`` collection: - .. code-block:: javascript +.. code-block:: javascript - db.bios.update( - { name: { first: 'Dennis', last: 'Ritchie'} }, - { - name: { first: 'Dennis', last: 'Ritchie'}, - birth: new Date('Sep 09, 1941'), - died: new Date('Oct 12, 2011'), - contribs: [ 'UNIX', 'C' ], - awards: [ - { - award: 'Turing Award', - year: 1983, - by: 'ACM' - }, - { - award: 'National Medal of Technology', - year: 1998, - by: 'United States' - }, - { - award: 'Japan Prize', - year: 2011, - by: 'The Japan Prize Foundation' - } - ] - }, - { upsert: true } - ) + db.bios.update( + { name: { first: 'Dennis', last: 'Ritchie'} }, + { + name: { first: 'Dennis', last: 'Ritchie'}, + birth: new Date('Sep 09, 1941'), + death: new Date('Oct 12, 2011'), + contribs: [ 'UNIX', 'C' ], + awards: [ + { + award: 'Turing Award', + year: 1983, + by: 'ACM' + }, + { + award: 'National Medal of Technology', + year: 1998, + by: 'United States' + }, + { + award: 'Japan Prize', + year: 2011, + by: 'The Japan Prize Foundation' + } + ] + }, + { upsert: true } + ) + +Insert a Document that Contains Update Operator Expressions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If no document matches the ```` argument, the upsert operation +inserts a new document. If the ```` argument includes only +:ref:`update operators `, the new document contains +the fields and values from ```` argument with the operations +from the ```` argument applied. + +The following operation inserts a new document into the ``bios`` +collection: -- If no document matches the ```` argument, the upsert operation - inserts a new document. If the ```` argument includes only - :ref:`update operators `, the new document contains - the fields and values from ```` argument with the operations - from the ```` argument applied. +.. code-block:: javascript - The following operation inserts a new document into the - ``bios`` collection: + db.bios.update( + { + _id: 7, + name: { first: 'Ken', last: 'Thompson' } + }, + { + $set: { + birth: new Date('Feb 04, 1943'), + contribs: [ 'UNIX', 'C', 'B', 'UTF-8' ], + awards: [ + { + award: 'Turing Award', + year: 1983, + by: 'ACM' + }, + { + award: 'IEEE Richard W. Hamming Medal', + year: 1990, + by: 'IEEE' + }, + { + award: 'National Medal of Technology', + year: 1998, + by: 'United States' + }, + { + award: 'Tsutomu Kanai Award', + year: 1999, + by: 'IEEE' + }, + { + award: 'Japan Prize', + year: 2011, + by: 'The Japan Prize Foundation' + } + ] + } + }, + { upsert: true } + ) - .. code-block:: javascript +.. _crud-create-save: - db.bios.update( - { - _id: 7, - name: { first: 'Ken', last: 'Thompson' } - }, - { - $set: { - birth: new Date('Feb 04, 1943'), - contribs: [ 'UNIX', 'C', 'B', 'UTF-8' ], - awards: [ - { - award: 'Turing Award', - year: 1983, - by: 'ACM' - }, - { - award: 'IEEE Richard W. Hamming Medal', - year: 1990, - by: 'IEEE' - }, - { - award: 'National Medal of Technology', - year: 1998, - by: 'United States' - }, - { - award: 'Tsutomu Kanai Award', - year: 1999, - by: 'IEEE' - }, - { - award: 'Japan Prize', - year: 2011, - by: 'The Japan Prize Foundation' - } - ] - } - }, - { upsert: true } - ) +Upsert with ``save()`` +~~~~~~~~~~~~~~~~~~~~~~ + +The :method:`~db.collection.save()` method performs an upsert if the +document to save contains the ``_id`` field. To determine whether to +perform an insert or an update, :method:`~db.collection.save()` method +queries documents on the ``_id`` field. + +The following operation performs an upsert that inserts a document into +the ``bios`` collection since no documents in the collection contains +an ``_id`` field with the value ``10``: + +.. code-block:: javascript + + db.bios.save( + { + _id: 10, + name: { first: 'Yukihiro', aka: 'Matz', last: 'Matsumoto'}, + birth: new Date('Apr 14, 1965'), + contribs: [ 'Ruby' ], + awards: [ + { + award: 'Award for the Advancement of Free Software', + year: '2011', + by: 'Free Software Foundation' + } + ] + } + ) diff --git a/source/applications/delete.txt b/source/applications/delete.txt index ae3572c7135..d3f3ba4d5eb 100644 --- a/source/applications/delete.txt +++ b/source/applications/delete.txt @@ -11,6 +11,12 @@ For general information about write operations and the factors that affect their performance, see :doc:`/core/write-operations`; for documentation of other CRUD operations, see the :doc:`/crud` page. +.. contents:: + :backlinks: none + :local: + +.. _crud-delete-remove: + Overview -------- @@ -22,11 +28,6 @@ shell provides this operation, as do corresponding methods in the .. include:: /includes/fact-write-concern.rst -.. _crud-delete-remove: - -Remove ------- - Use the :method:`~db.collection.remove()` method to delete documents from a collection. The :method:`~db.collection.remove()` method has the following syntax: @@ -52,74 +53,79 @@ collection, but does not remove the indexes. [#drop]_ .. note:: - For large deletion operations it may be more effect to copy the - documents that you want to save to a new collection and then use + For large deletion operations, it may be more efficient to copy the + documents that you want to keep to a new collection and then use :method:`~db.collection.drop()` on the original collection. -Consider the following examples that illustrate the use of the -:method:`~db.collection.remove()`: +Remove All Documents That Match a Condition +------------------------------------------- -- If there is a ```` argument, the :method:`remove() - ` method deletes from the collection all - documents that match the argument. +If there is a ```` argument, the +:method:`~db.collection.remove()` method deletes from the collection +all documents that match the argument. - The following operation deletes all documents from the ``bios`` - collection where the subdocument ``name`` contains a field ``first`` - whose value starts with ``G``: +The following operation deletes all documents from the ``bios`` +collection where the subdocument ``name`` contains a field ``first`` +whose value starts with ``G``: - .. code-block:: javascript +.. code-block:: javascript + + db.bios.remove( { 'name.first' : /^G/ } ) + +Remove Only One Document That Match a Condition +----------------------------------------------- - db.bios.remove( { 'name.first' : /^G/ } ) +If there is a ```` argument and you specify the ```` +argument as ``true`` or ``1``, :method:`~db.collection.remove()` only +deletes a single document from the collection that matches the query. -- If there is a ```` argument and you specify the ```` - argument as ``true`` or ``1``, :method:`remove() - ` only deletes a single document from the - collection that matches the query. +The following operation deletes a single document from the ``bios`` +collection where the ``turing`` field equals ``true``: - The following operation deletes a single document from the ``bios`` - collection where the ``turing`` field equals ``true``: +.. code-block:: javascript - .. code-block:: javascript + db.bios.remove( { turing: true }, 1 ) - db.bios.remove( { turing: true }, 1 ) +Remove All Documents from a Collection +-------------------------------------- -- If there is no ```` argument, the :method:`remove() - ` method deletes all documents from a - collection. The following operation deletes all documents from the - ``bios`` collection: +If there is no ```` argument, the +:method:`~db.collection.remove()` method deletes all documents from a +collection. The following operation deletes all documents from the +``bios`` collection: - .. code-block:: javascript +.. code-block:: javascript - db.bios.remove() + db.bios.remove() - .. note:: +.. note:: - This operation is not equivalent to the :method:`drop() - ` method. + This operation is not equivalent to the + :method:`~db.collection.drop()` method. -.. [#drop] To remove all documents from a collection, it may be faster - to use the :method:`drop() ` method to drop the - entire collection, including the indexes, and then recreate the - collection and rebuild the indexes. +.. [#drop] To remove all documents from a collection, it may be more + efficient to use the :method:`~db.collection.drop()` method + to drop the entire collection, including the indexes, and then + recreate the collection and rebuild the indexes. .. _crud-delete-remove-isolation: Capped Collection -~~~~~~~~~~~~~~~~~ +----------------- .. include:: /includes/fact-remove-capped-collection-restriction.rst Isolation -~~~~~~~~~ - -If the ```` argument to the :method:`remove() -` method matches multiple documents in the -collection, the delete operation may interleave with other write -operations to that collection. For an unsharded collection, you have -the option to override this behavior with the :operator:`$isolated` -isolation operator, effectively isolating the delete operation from -other write operations. To isolate the operation, include ``$isolated: -1`` in the ```` parameter as in the following example: +--------- + +If the ```` argument to the :method:`~db.collection.remove()` +method matches multiple documents in the collection, the delete +operation may interleave with other write operations to that +collection. For an unsharded collection, you have the option to +override this behavior with the :operator:`$isolated` isolation +operator, effectively isolating the delete operation from other write +operations. To isolate the operation, include ``$isolated: 1`` in the +```` parameter as in the following example: .. code-block:: javascript diff --git a/source/applications/read.txt b/source/applications/read.txt index c8a6c9052a6..7cf20ee9de8 100644 --- a/source/applications/read.txt +++ b/source/applications/read.txt @@ -11,6 +11,10 @@ operations and the factors that affect their performance, see :doc:`/core/read-operations`; for documentation of the other CRUD operations, see the :doc:`/crud` page. +.. contents:: + :backlinks: none + :local: + Overview -------- @@ -23,16 +27,15 @@ methods: .. _crud-read-find: -Find ----- +``find()`` +---------- -The :method:`find() ` method is the primary -method to select documents from a collection. The :method:`find() -` method returns a cursor that contains a number -of documents. Most :doc:`drivers ` provide -application developers with a native iterable interface for handling -cursors and accessing documents. -The :method:`find() ` method has the following +The :method:`~db.collection.find()` method is the primary method to +select documents from a collection. The :method:`~db.collection.find()` +method returns a cursor that contains a number of documents. Most +:doc:`drivers ` provide application developers +with a native iterable interface for handling cursors and accessing +documents. The :method:`~db.collection.find()` method has the following syntax: .. code-block:: javascript @@ -41,7 +44,7 @@ syntax: .. admonition:: Corresponding Operation in SQL - The :method:`find() ` method is analogous to + The :method:`~db.collection.find()` method is analogous to the ``SELECT`` statement, while: - the ```` argument corresponds to the ``WHERE`` statement, @@ -50,9 +53,6 @@ syntax: - the ```` argument corresponds to the list of fields to select from the result set. -Consider the following examples that illustrate the use of the -:method:`find() ` method: - .. pull-quote:: The examples refer to a collection named ``bios`` that contains documents with the following prototype: @@ -94,302 +94,371 @@ Consider the following examples that illustrate the use of the .. note:: In the :program:`mongo` shell, you can format the output by adding - ``.pretty()`` to the :method:`find() ` method - call. + ``.pretty()`` to the :method:`~db.collection.find()` method call. -- If there is no ```` argument, the :method:`find() - ` method selects all documents from a collection. +Return All Documents in a Collection +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - The following operation returns all documents (or more - precisely, a cursor to all documents) in the ``bios`` - collection: +If there is no ```` argument, the :method:` +~db.collection.find()` method selects all documents from a collection. - .. code-block:: javascript +The following operation returns all documents (or more precisely, a +cursor to all documents) in the ``bios`` collection: - db.bios.find() +.. code-block:: javascript -- If there is a ```` argument, the :method:`find() - ` method selects all documents from a - collection that satisfies the criteria of the query: + db.bios.find() - - The following operation returns all documents in the ``bios`` - collection where the field ``_id`` equals ``5`` or - ``ObjectId("507c35dd8fada716c89d0013")``: +Return Documents that Match Query Conditions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - .. code-block:: javascript +If there is a ```` argument, the :method:`~db.collection.find()` +method selects all documents from a collection that satisfies the query +specification. - db.bios.find( - { - _id: { $in: [ 5, ObjectId("507c35dd8fada716c89d0013") ] } - } - ) +Equality Matches +```````````````` - - The following operation returns all documents in the ``bios`` - collection where the array field ``contribs`` contains the element - ``'UNIX'``: +The following operation returns a cursor to documents in the ``bios`` +collection where the field ``_id`` equals ``5``: - .. code-block:: javascript +.. code-block:: javascript - db.bios.find( - { - contribs: 'UNIX' - } - ) + db.bios.find( + { + _id: 5 + } + ) - - The following operation returns all documents in the ``bios`` - collection where ``awards`` array contains a subdocument element - that contains the ``award`` field equal to ``'Turing Award'`` and the - ``year`` field greater than 1980: +Using Operators +``````````````` - .. code-block:: javascript +The following operation returns a cursor to all documents in the +``bios`` collection where the field ``_id`` equals ``5`` or +``ObjectId("507c35dd8fada716c89d0013")``: - db.bios.find( - { - awards: { - $elemMatch: { - award: 'Turing Award', - year: { $gt: 1980 } - } - } - } - ) +.. code-block:: javascript - - The following operation returns all documents in the ``bios`` - collection where the subdocument ``name`` contains a field - ``first`` with the value ``'Yukihiro'`` and a field ``last`` with - the value ``'Matsumoto'``; the query uses :term:`dot notation` to - access fields in a subdocument: + db.bios.find( + { + _id: { $in: [ 5, ObjectId("507c35dd8fada716c89d0013") ] } + } + ) - .. code-block:: javascript +On Arrays +````````` - db.bios.find( - { - 'name.first': 'Yukihiro', - 'name.last': 'Matsumoto' - } - ) +Query an Element +^^^^^^^^^^^^^^^^ - The query matches the document where the ``name`` field contains a - subdocument with the field ``first`` with the value ``'Yukihiro'`` - and a field ``last`` with the value ``'Matsumoto'``. For instance, - the query would match documents with ``name`` fields that - held either of the following values: +The following operation returns a cursor to all documents in the +``bios`` collection where the array field ``contribs`` contains the +element ``'UNIX'``: - .. code-block:: javascript +.. code-block:: javascript - { - first: 'Yukihiro', - aka: 'Matz', - last: 'Matsumoto' - } + db.bios.find( + { + contribs: 'UNIX' + } + ) - { - last: 'Matsumoto', - first: 'Yukihiro' - } +Query Multiple Fields on an Array of Documents +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following operation returns a cursor to all documents in the +``bios`` collection where ``awards`` array contains a subdocument +element that contains the ``award`` field equal to ``'Turing Award'`` +and the ``year`` field greater than 1980: - - The following operation returns all documents in the ``bios`` - collection where the subdocument ``name`` is *exactly* ``{ first: - 'Yukihiro', last: 'Matsumoto' }``, including the order: +.. code-block:: javascript - .. code-block:: javascript + db.bios.find( + { + awards: { + $elemMatch: { + award: 'Turing Award', + year: { $gt: 1980 } + } + } + } + ) - db.bios.find( - { - name: { - first: 'Yukihiro', - last: 'Matsumoto' - } - } - ) +On Subdocuments +``````````````` - The ``name`` field must match the sub-document exactly, including - order. For instance, the query would **not** match documents with - ``name`` fields that held either of the following values: +Exact Matches +^^^^^^^^^^^^^ - .. code-block:: javascript +The following operation returns a cursor to all documents in the +``bios`` collection where the subdocument ``name`` is *exactly* ``{ +first: 'Yukihiro', last: 'Matsumoto' }``, including the order: - { - first: 'Yukihiro', - aka: 'Matz', - last: 'Matsumoto' - } +.. code-block:: javascript + db.bios.find( { - last: 'Matsumoto', - first: 'Yukihiro' + name: { + first: 'Yukihiro', + last: 'Matsumoto' + } } + ) + +The ``name`` field must match the sub-document exactly, including +order. For instance, the query would **not** match documents with +``name`` fields that held either of the following values: + +.. code-block:: javascript + + { + first: 'Yukihiro', + aka: 'Matz', + last: 'Matsumoto' + } + + { + last: 'Matsumoto', + first: 'Yukihiro' + } + +Fields of a Subdocument +^^^^^^^^^^^^^^^^^^^^^^^ + +The following operation returns a cursor to all documents in the +``bios`` collection where the subdocument ``name`` contains a field +``first`` with the value ``'Yukihiro'`` and a field ``last`` with the +value ``'Matsumoto'``; the query uses :term:`dot notation` to access +fields in a subdocument: + +.. code-block:: javascript + + db.bios.find( + { + 'name.first': 'Yukihiro', + 'name.last': 'Matsumoto' + } + ) + +The query matches the document where the ``name`` field contains a +subdocument with the field ``first`` with the value ``'Yukihiro'`` and +a field ``last`` with the value ``'Matsumoto'``. For instance, the +query would match documents with ``name`` fields that held either of +the following values: + +.. code-block:: javascript + + { + first: 'Yukihiro', + aka: 'Matz', + last: 'Matsumoto' + } + + { + last: 'Matsumoto', + first: 'Yukihiro' + } + +Logical Operators +````````````````` + +``OR`` Disjunctions +^^^^^^^^^^^^^^^^^^^ + +The following operation returns a cursor to all documents in the +``bios`` collection where either the field ``first`` in the +sub-document ``name`` starts with the letter ``G`` **or** where the +field ``birth`` is less than ``new Date('01/01/1945')``: + +.. code-block:: javascript + + db.bios.find( + { $or: [ + { 'name.first' : /^G/ }, + { birth: { $lt: new Date('01/01/1945') } } + ] + } + ) + +``AND`` Conjunctions +^^^^^^^^^^^^^^^^^^^^ + +The following operation returns a cursor to all documents in the +``bios`` collection where the field ``first`` in the subdocument +``name`` starts with the letter ``K`` **and** the array field +``contribs`` contains the element ``UNIX``: + +.. code-block:: javascript + + db.bios.find( + { + 'name.first': /^K/, + contribs: 'UNIX' + } + ) + +In this query, the parameters (i.e. the selections of both fields) +combine using an implicit logical AND for criteria on different fields +``contribs`` and ``name.first``. For multiple ``AND`` criteria on the +same field, use the :operator:`$and` operator. + +With a Projection +~~~~~~~~~~~~~~~~~ + +If there is a ```` argument, the +:method:`~db.collection.find()` method returns only those fields as +specified in the ```` argument to include or exclude: + +.. note:: The ``_id`` field is implicitly included in the + ```` argument. In projections that explicitly include + fields, ``_id`` is the only field that you can explicitly exclude. + Otherwise, you cannot mix include field and exclude field + specifications. + +Specify the Fields to Return +```````````````````````````` + +The following operation finds all documents in the ``bios`` collection +and returns only the ``name`` field, the ``contribs`` field, and the +``_id`` field: + +.. code-block:: javascript + + db.bios.find( + { }, + { name: 1, contribs: 1 } + ) + +Explicitly Exclude the ``_id`` Field +```````````````````````````````````` - - The following operation returns all documents in the ``bios`` - collection where either the field ``first`` in the sub-document - ``name`` starts with the letter ``G`` **or** where the field - ``birth`` is less than ``new Date('01/01/1945')``: - - .. code-block:: javascript - - db.bios.find( - { $or: [ - { 'name.first' : /^G/ }, - { birth: { $lt: new Date('01/01/1945') } } - ] - } - ) - - - The following operation returns all documents in the ``bios`` - collection where the field ``first`` in the subdocument ``name`` - starts with the letter ``K`` **and** the array field ``contribs`` - contains the element ``UNIX``: - - .. code-block:: javascript - - db.bios.find( - { - 'name.first': /^K/, - contribs: 'UNIX' - } - ) - - In this query, the parameters (i.e. the selections of both fields) - combine using an implicit logical AND for criteria on different - fields ``contribs`` and ``name.first``. For multiple AND criteria - on the same field, use the :operator:`$and` operator. - -- If there is a ```` argument, the :method:`find() - ` method returns only those fields as specified - in the ```` argument to include or exclude: - - .. note:: The ``_id`` field is implicitly included in the - ```` argument. In projections that explicitly include - fields, ``_id`` is the only field that you can explicitly exclude. - Otherwise, you cannot mix include field and exclude field - specifications. - - - The following operation finds all documents in the ``bios`` - collection and returns only the ``name`` field, the ``contribs`` - field, and the ``_id`` field: - - .. code-block:: javascript - - db.bios.find( - { }, - { name: 1, contribs: 1 } - ) - - - The following operation finds all documents in the ``bios`` - collection and returns only the ``name`` field and the ``contribs`` - field: - - .. code-block:: javascript - - db.bios.find( - { }, - { name: 1, contribs: 1, _id: 0 } - ) - - - The following operation finds the documents in the ``bios`` - collection where the ``contribs`` field contains the element - ``'OOP'`` and returns all fields *except* the ``_id`` field, the - ``first`` field in the ``name`` subdocument, and the ``birth`` - field from the matching documents: - - .. code-block:: javascript - - db.bios.find( - { contribs: 'OOP' }, - { _id: 0, 'name.first': 0, birth: 0 } - ) - - - The following operation finds all documents in the ``bios`` - collection and returns the the ``last`` field in the ``name`` - subdocument and the first two elements in the ``contribs`` field: - - .. code-block:: javascript - - db.bios.find( - { }, - { - _id: 0, - 'name.last': 1, - contribs: { $slice: 2 } - } - ) +The following operation finds all documents in the ``bios`` collection +and returns only the ``name`` field and the ``contribs`` field: + +.. code-block:: javascript + + db.bios.find( + { }, + { name: 1, contribs: 1, _id: 0 } + ) + +Return All but the Excluded Fields +`````````````````````````````````` + +The following operation finds the documents in the ``bios`` collection +where the ``contribs`` field contains the element ``'OOP'`` and returns +all fields *except* the ``_id`` field, the ``first`` field in the +``name`` subdocument, and the ``birth`` field from the matching +documents: + +.. code-block:: javascript + + db.bios.find( + { contribs: 'OOP' }, + { _id: 0, 'name.first': 0, birth: 0 } + ) + +On Arrays and Subdocuments +`````````````````````````` + +The following operation finds all documents in the ``bios`` collection +and returns the the ``last`` field in the ``name`` subdocument and the +first two elements in the ``contribs`` array: + +.. code-block:: javascript + + db.bios.find( + { }, + { + _id: 0, + 'name.last': 1, + contribs: { $slice: 2 } + } + ) .. seealso:: - :term:`dot notation` for information on "reaching into" embedded sub-documents. - - :ref:`read-operations-arrays` for more examples on accessing arrays + - :ref:`read-operations-arrays` for more examples on accessing arrays. - :ref:`read-operations-subdocuments` for more examples on accessing - subdocuments + subdocuments. + + - :method:`$elemMatch` query operator for more information on + matching array elements. + + - :projection:`$elemMatch` projection operator for additional + information on restricting array elements to return. .. _crud-read-cursor: -Cursor -~~~~~~ +Iterate the Returned Cursor +~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The :method:`find() ` method returns a -:term:`cursor` to the results; however, in the :program:`mongo` shell, -if the returned cursor is not assigned to a variable, then the cursor -is automatically iterated up to 20 times [#setShellBatchSize]_ to print -up to the first 20 documents that match the query, as in the following -example: +The :method:`~db.collection.find()` method returns a :term:`cursor` to +the results; however, in the :program:`mongo` shell, if the returned +cursor is not assigned to a variable, then the cursor is automatically +iterated up to 20 times [#setShellBatchSize]_ to print up to the first +20 documents that match the query, as in the following example: .. code-block:: javascript db.bios.find( { _id: 1 } ); -When you assign the :method:`find() ` to a -variable: +With Variable Name +`````````````````` -- you can type the name of the cursor variable to iterate up to 20 - times [#setShellBatchSize]_ and print the matching documents, as in - the following example: +When you assign the :method:`~db.collection.find()` to a variable, you +can type the name of the cursor variable to iterate up to 20 times +[#setShellBatchSize]_ and print the matching documents, as in the +following example: - .. code-block:: javascript - - var myCursor = db.bios.find( { _id: 1 } ); - - myCursor +.. code-block:: javascript -- you can use the cursor method :method:`next() ` to - access the documents, as in the following example: + var myCursor = db.bios.find( { _id: 1 } ); - .. code-block:: javascript + myCursor - var myCursor = db.bios.find( { _id: 1 } ); +With ``next()`` Method +`````````````````````` - var myDocument = myCursor.hasNext() ? myCursor.next() : null; +You can use the cursor method :method:`~cursor.next()` to +access the documents, as in the following example: - if (myDocument) { +.. code-block:: javascript - var myName = myDocument.name; + var myCursor = db.bios.find( { _id: 1 } ); - print (tojson(myName)); - } + var myDocument = myCursor.hasNext() ? myCursor.next() : null; - To print, you can also use the ``printjson()`` method instead of - ``print(tojson())``: + if (myDocument) { + var myName = myDocument.name; + print (tojson(myName)); + } - .. code-block:: javascript +To print, you can also use the ``printjson()`` method instead of +``print(tojson())``: - if (myDocument) { +.. code-block:: javascript - var myName = myDocument.name; + if (myDocument) { + var myName = myDocument.name; + printjson(myName); + } - printjson(myName); - } +With ``forEach()`` Method +````````````````````````` -- you can use the cursor method :method:`forEach() ` - to iterate the cursor and access the documents, as in the following - example: +You can use the cursor method :method:`~cursor.forEach()` to iterate +the cursor and access the documents, as in the following example: - .. code-block:: javascript +.. code-block:: javascript - var myCursor = db.bios.find( { _id: 1 } ); + var myCursor = db.bios.find( { _id: 1 } ); - myCursor.forEach(printjson); + myCursor.forEach(printjson); For more information on cursor handling, see: @@ -407,59 +476,71 @@ For more information on cursor handling, see: change the number of iteration from the default value ``20``. See :ref:`cursor-flags` and :ref:`cursor-behaviors` for more information. -Modify Cursor Behavior -`````````````````````` +Modify the Cursor Behavior +~~~~~~~~~~~~~~~~~~~~~~~~~~ In addition to the ```` and the ```` arguments, the :program:`mongo` shell and the :doc:`drivers ` provide several cursor methods that you can call on the *cursor* -returned by :method:`find() ` method to modify +returned by :method:`~db.collection.find()` method to modify its behavior, such as: -- :method:`sort `, which orders the documents in the - result set according to the field or fields specified to the method. +Order Documents in the Result Set +````````````````````````````````` - The following operation returns all documents (or more precisely, a - cursor to all documents) in the ``bios`` collection ordered by the - ``name`` field ascending: +The :method:`~cursor.sort()` method orders the documents in the +result set. - .. code-block:: javascript +The following operation returns all documents (or more precisely, a +cursor to all documents) in the ``bios`` collection ordered by the +``name`` field ascending: - db.bios.find().sort( { name: 1 } ) +.. code-block:: javascript - :method:`sort() ` corresponds to the ``ORDER BY`` - statement in SQL. + db.bios.find().sort( { name: 1 } ) -- The :method:`limit() ` method limits the number of - documents in the result set. +:method:`~cursor.sort()` corresponds to the ``ORDER BY`` +statement in SQL. - The following operation returns at most ``5`` documents (or more - precisely, a cursor to at most 5 documents) in the ``bios`` - collection: +Limit the Number of Documents to Return +``````````````````````````````````````` - .. code-block:: javascript +The :method:`~cursor.limit()` method limits the number of +documents in the result set. - db.bios.find().limit( 5 ) +The following operation returns at most ``5`` documents (or more +precisely, a cursor to at most 5 documents) in the ``bios`` collection: - :method:`limit() ` corresponds to the ``LIMIT`` - statement in SQL. +.. code-block:: javascript -- The :method:`skip() ` method controls the starting - point of the results set. + db.bios.find().limit( 5 ) - The following operation returns all documents, skipping the first - ``5`` documents in the ``bios`` collection: +:method:`~cursor.limit()` corresponds to the ``LIMIT`` +statement in SQL. - .. code-block:: javascript +Set the Starting Point of the Result Set +```````````````````````````````````````` - db.bios.find().skip( 5 ) +The :method:`~cursor.skip()` method controls the starting point +of the results set. -You can chain these cursor methods, as in the following examples [#dbquery-server]_: +The following operation returns all documents, skipping the first ``5`` +documents in the ``bios`` collection: - .. code-block:: javascript +.. code-block:: javascript - db.bios.find().sort( { name: 1 } ).limit( 5 ) - db.bios.find().limit( 5 ).sort( { name: 1 } ) + db.bios.find().skip( 5 ) + +Combine Cursor Methods +`````````````````````` + +You can chain these cursor methods, as in the following examples +[#dbquery-server]_: + +.. code-block:: javascript + + db.bios.find().sort( { name: 1 } ).limit( 5 ) + db.bios.find().limit( 5 ).sort( { name: 1 } ) See the :ref:`JavaScript cursor methods ` reference and your :doc:`driver ` documentation @@ -467,109 +548,123 @@ for additional references. See :ref:`read-operations-cursors` for more information regarding cursors. .. [#dbquery-server] Regardless of the order you chain the - :method:`limit() ` and the :method:`sort() - `, the request to the server has the following - structure that treats the query and the :method:`sort() - ` modifier as a single object. Therefore, the - :method:`limit() ` operation method is always - applied after the :method:`sort() ` regardless of - the specified order of the operations in the chain. See the - :doc:`meta query operators ` for - more information. + :method:`~cursor.limit()` and the :method:`~cursor.sort()`, the + request to the server has the structure that treats the + query and the :method:` ~cursor.sort()` modifier as a single object. + Therefore, the :method:`~cursor.limit()` operation method is always + applied after the :method:`~cursor.sort()` regardless of the + specified order of the operations in the chain. See the :doc:`meta + query operators ` for more + information. .. _crud-read-findOne: .. _crud-read-find-one: -Find One --------- +``findOne()`` +------------- -The :method:`findOne() ` method selects and +The :method:`~db.collection.findOne()` method selects and returns a single document from a collection and returns that -document. :method:`findOne() ` does *not* +document. :method:`~db.collection.findOne()` does *not* return a cursor. -The :method:`findOne() ` method has the following +The :method:`~db.collection.findOne()` method has the following syntax: .. code-block:: javascript db.collection.findOne( , ) -Except for the return value, :method:`findOne() -` method is quite similar to the -:method:`find() ` method; in fact, internally, -the :method:`findOne() ` method is the -:method:`find() ` method with a limit of 1. - -Consider the following examples that illustrate the use of the -:method:`findOne() ` method: - -- If there is no ```` argument, the :method:`findOne() - ` method selects just one document from a - collection. - - - The following operation returns a single document from the - ``bios`` collection: - - .. code-block:: javascript - - db.bios.findOne() - -- If there is a ```` argument, the :method:`findOne() - ` method selects the first document from a - collection that meets the ```` argument: - - - The following operation returns the first matching document from - the ``bios`` collection where either the field ``first`` in the - subdocument ``name`` starts with the letter ``G`` **or** where the - field ``birth`` is less than ``new Date('01/01/1945')``: - - .. code-block:: javascript - - db.bios.findOne( - { - $or: [ - { 'name.first' : /^G/ }, - { birth: { $lt: new Date('01/01/1945') } } - ] - } - ) - -- You can pass a ```` argument to :method:`findOne() - ` to control the fields included in the - result set: - - - The following operation finds a document in the ``bios`` - collection and returns only the ``name`` field, the ``contribs`` - field, and the ``_id`` field: - - .. code-block:: javascript - - db.bios.findOne( - { }, - { name: 1, contribs: 1 } - ) - - - The following operation returns a document in the ``bios`` - collection where the ``contribs`` field contains the element - ``OOP`` and returns all fields *except* the ``_id`` field, the - ``first`` field in the ``name`` subdocument, and the ``birth`` - field from the matching documents: - - .. code-block:: javascript - - db.bios.findOne( - { contribs: 'OOP' }, - { _id: 0, 'name.first': 0, birth: 0 } - ) - -Although similar to the :method:`find() ` method, -because the :method:`findOne() ` method -returns a document rather than a cursor, you cannot apply the cursor -methods such as :method:`limit() `, :method:`sort() -`, and :method:`skip() ` to the result of -the :method:`findOne() ` method. However, you -can access the document directly, as in the following example: +Except for the return value, :method:`~db.collection.findOne()` method +is quite similar to the :method:`~db.collection.find()` method; in +fact, internally, the :method:`~db.collection.findOne()` method is the +:method:`~db.collection.find()` method with a limit of 1. + + +With Empty Query Specification +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If there is no ```` argument, the +:method:`~db.collection.findOne()` method selects just one document +from a collection. + +The following operation returns a single document from the ``bios`` +collection: + +.. code-block:: javascript + + db.bios.findOne() + +With a Query Specification +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If there is a ```` argument, the +:method:`~db.collection.findOne()` method selects the first document +from a collection that meets the ```` argument: + +The following operation returns the first matching document from the +``bios`` collection where either the field ``first`` in the subdocument +``name`` starts with the letter ``G`` **or** where the field ``birth`` +is less than ``new Date('01/01/1945')``: + +.. code-block:: javascript + + db.bios.findOne( + { + $or: [ + { 'name.first' : /^G/ }, + { birth: { $lt: new Date('01/01/1945') } } + ] + } + ) + +With a Projection +~~~~~~~~~~~~~~~~~ + +You can pass a ```` argument to +:method:`~db.collection.findOne()` to control the fields included in +the result set. + +Specify the Fields to Return +```````````````````````````` + +The following operation finds a document in the ``bios`` collection and +returns only the ``name`` field, the ``contribs`` field, and the +``_id`` field: + +.. code-block:: javascript + + db.bios.findOne( + { }, + { name: 1, contribs: 1 } + ) + +Return All but the Excluded Fields +`````````````````````````````````` + +The following operation returns a document in the ``bios`` collection +where the ``contribs`` field contains the element ``OOP`` and returns +all fields *except* the ``_id`` field, the ``first`` field in the +``name`` subdocument, and the ``birth`` field from the matching +documents: + +.. code-block:: javascript + + db.bios.findOne( + { contribs: 'OOP' }, + { _id: 0, 'name.first': 0, birth: 0 } + ) + +Access the ``findOne`` Result +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Although similar to the :method:`~db.collection.find()` method, because +the :method:`~db.collection.findOne()` method returns a document rather +than a cursor, you cannot apply the cursor methods such as +:method:`~cursor.limit()`, :method:`~cursor.sort()`, and +:method:`~cursor.skip()` to the result of the +:method:`~db.collection.findOne()` method. However, you can +access the document directly, as in the example: .. code-block:: javascript diff --git a/source/applications/update.txt b/source/applications/update.txt index e5077055868..6539757aeaa 100644 --- a/source/applications/update.txt +++ b/source/applications/update.txt @@ -11,6 +11,10 @@ operations and the factors that affect their performance, see :doc:`/core/write-operations`; for documentation of other CRUD operations, see the :doc:`/crud` page. +.. contents:: + :backlinks: none + :local: + Overview -------- @@ -34,18 +38,16 @@ methods to perform update operations: Update ------ -The :method:`update() ` method is the primary -method used to modify documents in a MongoDB collection. By default, -the :method:`update() ` method updates a -**single** document, but by using the ``multi`` option, -:method:`update() ` can update all documents -that match the query criteria in the collection. The :method:`update() -` method can either replace the existing -document with the new document or update specific fields in the -existing document. +The :method:`~db.collection.update()` method is the primary method used +to modify documents in a MongoDB collection. By default, the +:method:`~db.collection.update()` method updates a **single** document, +but by using the ``multi`` option, :method:`~db.collection.update()` +can update all documents that match the query criteria in the +collection. The :method:`~db.collection.update()` method can either +replace the existing document with the new document or update specific +fields in the existing document. -The :method:`update() ` has the following -syntax: +The :method:`~db.collection.update()` has the following syntax: .. code-block:: javascript @@ -53,289 +55,320 @@ syntax: .. admonition:: Corresponding operation in SQL - The :method:`update() ` method corresponds - to the ``UPDATE`` operation in SQL, and: + The :method:`~db.collection.update()` method corresponds to the + ``UPDATE`` operation in SQL, and: - the ```` argument corresponds to the ``WHERE`` statement, and - the ```` corresponds to the ``SET ...`` statement. - The default behavior of the :method:`update() - ` method updates a **single** document and - would correspond to the SQL ``UPDATE`` statement with the ``LIMIT - 1``. With the ``multi`` option, :method:`update() - ` method would correspond to the SQL - ``UPDATE`` statement without the ``LIMIT`` clause. - -Consider the following examples that illustrate the use of the -:method:`update() ` method: - -- If the ```` argument contains only :ref:`update operator - ` expressions such as the :operator:`$set` operator - expression, the :method:`update() ` method - updates the corresponding fields in the document. To update fields in - subdocuments, MongoDB uses :term:`dot notation`. - - The following operation queries the ``bios`` collection for the first - document that has an ``_id`` field equal to ``1`` and sets the field - named ``middle`` to the value ``Warner`` in the ``name`` subdocument - and adds a new element to the ``awards`` field: - - .. code-block:: javascript - - db.bios.update( - { _id: 1 }, - { - $set: { 'name.middle': 'Warner' }, - $push: { awards: { award: 'IBM Fellow', year: 1963, by: 'IBM' } } - } - ) - -- If the ```` argument contains :operator:`$unset` operator, the - :method:`update() ` method removes the field - from the document. - - The following operation queries the ``bios`` collection for the - first document that has an ``_id`` field equal to ``3`` and removes - the ``birth`` field from the document: - - .. code-block:: javascript - - db.bios.update( - { _id: 3 }, - { $unset: { birth: 1 } } - ) - -- If the ```` argument contains fields not currently in the - document, the :method:`update() ` method - adds the new fields to the document. - - The following operation queries the ``bios`` collection for the - first document that has an ``_id`` field equal to ``3`` and adds to - the document a new ``mbranch`` field and a new ``aka`` field in the - subdocument ``name``: - - .. code-block:: javascript - - db.bios.update( - { _id: 3 }, - { $set: { - mbranch: 'Navy', - 'name.aka': 'Amazing Grace' - } - } - ) - -- If the ```` argument contains only field and value pairs, the - :method:`update() ` method *replaces* the - existing document with the document in the ```` argument, - except for the ``_id`` field. - - The following operation queries the ``bios`` collection for the - first document that has a ``name`` field equal to ``{ first: 'John', - last: 'McCarthy' }`` and replaces all but the ``_id`` field in the - document with the fields in the ```` argument: - - .. code-block:: javascript - - db.bios.update( - { name: { first: 'John', last: 'McCarthy' } }, - { name: { first: 'Ken', last: 'Iverson' }, - born: new Date('Dec 17, 1941'), - died: new Date('Oct 19, 2004'), - contribs: [ 'APL', 'J' ], - awards: [ - { award: 'Turing Award', - year: 1979, - by: 'ACM' }, - { award: 'Harry H. Goode Memorial Award', - year: 1975, - by: 'IEEE Computer Society' }, - { award: 'IBM Fellow', - year: 1970, - by: 'IBM' } - ] - } - ) - -- If the update operation requires an update of an element in an array - field: - - - The :method:`update() ` method can perform - the update using the position of the element and - :term:`dot notation`. Arrays in MongoDB are zero-based. - - The following operation queries the ``bios`` collection for - the first document with ``_id`` field equal to ``1`` and updates the - second element in the ``contribs`` array: - - .. code-block:: javascript - - db.bios.update( - { _id: 1 }, - { $set: { 'contribs.1': 'ALGOL 58' } } - ) + The default behavior of the :method:`~db.collection.update()` method + updates a **single** document and would correspond to the SQL + ``UPDATE`` statement with the ``LIMIT 1``. With the ``multi`` + option, :method:`~db.collection.update()` method would correspond to + the SQL ``UPDATE`` statement without the ``LIMIT`` clause. + +Modify with Update Operators +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If the ```` argument contains only :ref:`update operator +` expressions such as the :operator:`$set` +operator expression, the :method:`~db.collection.update()` +method updates the corresponding fields in the document. To update +fields in subdocuments, MongoDB uses :term:`dot notation`. + +Update a Field in a Document +```````````````````````````` + +Use :operator:`$set` to update a value of a field. + +The following operation queries the ``bios`` collection for the first +document that has an ``_id`` field equal to ``1`` and sets the value of +the field ``middle``, in the subdocument ``name``, to ``Warner``: + +.. code-block:: javascript + + db.bios.update( + { _id: 1 }, + { + $set: { 'name.middle': 'Warner' }, + } + ) + +Add a New Field to a Document +````````````````````````````` + +If the ```` argument contains fields not currently in the +document, the :method:`~db.collection.update()` method adds +the new fields to the document. + +The following operation queries the ``bios`` collection for the first +document that has an ``_id`` field equal to ``3`` and adds to that +document a new ``mbranch`` field and a new ``aka`` field in the +subdocument ``name``: + +.. code-block:: javascript + + db.bios.update( + { _id: 3 }, + { $set: { + mbranch: 'Navy', + 'name.aka': 'Amazing Grace' + } + } + ) - - The :method:`update() ` method can perform - the update using the :operator:`$` positional operator if the - position is not known. The array field must appear in the ``query`` - argument in order to determine which array element to update. +Remove a Field from a Document +`````````````````````````````` - The following operation queries the ``bios`` collection for the first - document where the ``_id`` field equals ``3`` and the ``contribs`` - array contains an element equal to ``compiler``. If found, the - :method:`update() ` method updates the - first matching element in the array to ``A compiler`` in the - document: +If the ```` argument contains :operator:`$unset` operator, the +:method:`~db.collection.update()` method removes the field +from the document. - .. code-block:: javascript +The following operation queries the ``bios`` collection for the first +document that has an ``_id`` field equal to ``3`` and removes the +``birth`` field from the document: + +.. code-block:: javascript + + db.bios.update( + { _id: 3 }, + { $unset: { birth: 1 } } + ) + +Update Arrays +````````````` + +Update an Element by Specifying Its Position +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If the update operation requires an update of an element in an array +field, the :method:`~db.collection.update()` method can +perform the update using the position of the element and :term:`dot +notation`. Arrays in MongoDB are zero-based. + +The following operation queries the ``bios`` collection for +the first document with ``_id`` field equal to ``1`` and updates the +second element in the ``contribs`` array: + +.. code-block:: javascript + + db.bios.update( + { _id: 1 }, + { $set: { 'contribs.1': 'ALGOL 58' } } + ) + +Update an Element without Specifying Its Position +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The :method:`~db.collection.update()` method can perform the +update using the :operator:`$` positional operator if the position is +not known. The array field must appear in the ``query`` argument in +order to determine which array element to update. + +The following operation queries the ``bios`` collection for the first +document where the ``_id`` field equals ``3`` and the ``contribs`` +array contains an element equal to ``compiler``. If found, the +:method:`~db.collection.update()` method updates the first +matching element in the array to ``A compiler`` in the document: + +.. code-block:: javascript - db.bios.update( + db.bios.update( { _id: 3, 'contribs': 'compiler' }, { $set: { 'contribs.$': 'A compiler' } } ) - - The :method:`update() ` method can perform - the update of an array that contains subdocuments by using the - positional operator (i.e. :operator:`$`) and the :term:`dot notation`. +Update a Document Element without Specifying Its Position +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - The following operation queries the ``bios`` collection for the first - document where the ``_id`` field equals ``6`` and the ``awards`` - array contains a subdocument element with the ``by`` field equal - to ``ACM``. If found, the :method:`update() - ` method updates the ``by`` field in the - first matching subdocument: +The :method:`~db.collection.update()` method can perform the +update of an array that contains subdocuments by using the positional +operator (i.e. :operator:`$`) and the :term:`dot notation`. - .. code-block:: javascript +The following operation queries the ``bios`` collection for the first +document where the ``_id`` field equals ``6`` and the ``awards`` array +contains a subdocument element with the ``by`` field equal to ``ACM``. +If found, the :method:`~db.collection.update()` method +updates the ``by`` field in the first matching subdocument: - db.bios.update( - { _id: 6, 'awards.by': 'ACM' } , - { $set: { 'awards.$.by': 'Association for Computing Machinery' } } - ) +.. code-block:: javascript + + db.bios.update( + { _id: 6, 'awards.by': 'ACM' } , + { $set: { 'awards.$.by': 'Association for Computing Machinery' } } + ) + +Add an Element to an Array +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following operation queries the ``bios`` collection for the first +document that has an ``_id`` field equal to ``1`` and adds a new +element to the ``awards`` field: + +.. code-block:: javascript + + db.bios.update( + { _id: 1 }, + { + $push: { awards: { award: 'IBM Fellow', year: 1963, by: 'IBM' } } + } + ) + +Update Multiple Documents +````````````````````````` + +If the ```` argument contains the ``multi`` option set to +``true`` or ``1``, the :method:`~db.collection.update()` +method updates all documents that match the query. + +The following operation queries the ``bios`` collection for all +documents where the ``awards`` field contains a subdocument element +with the ``award`` field equal to ``Turing`` and sets the ``turing`` +field to ``true`` in the matching documents: + +.. code-block:: javascript + + db.bios.update( + { 'awards.award': 'Turing' }, + { $set: { turing: true } }, + { multi: true } + ) + +Replace Existing Document with New Document +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- If the ```` argument contains the ``multi`` option set to - ``true`` or ``1``, the :method:`update() ` - method updates all documents that match the query. - - The following operation queries the ``bios`` collection for all - documents where the ``awards`` field contains a subdocument element - with the ``award`` field equal to ``Turing`` and sets the ``turing`` - field to ``true`` in the matching documents: - - .. code-block:: javascript - - db.bios.update( - { 'awards.award': 'Turing' }, - { $set: { turing: true } }, - { multi: true } - ) - -- If you set the ``upsert`` option in the ```` argument to - ``true`` or ``1`` and no existing document match the ```` - argument, the :method:`update() ` method can - insert a new document into the collection. - - The following operation queries the ``bios`` collection for a - document with the ``_id`` field equal to ``11`` and the ``name`` - field equal to ``{ first: 'James', last: 'Gosling'}``. If the query - selects a document, the operation performs an update operation. If a - document is not found, :method:`update() ` - inserts a new document containing the fields and values from - ```` argument with the operations from the ```` - argument applied. [#upsert-update-operators]_ - - .. code-block:: javascript - - db.bios.update( - { _id:11, name: { first: 'James', last: 'Gosling' } }, - { - $set: { - born: new Date('May 19, 1955'), - contribs: [ 'Java' ], - awards: [ - { award: 'The Economist Innovation Award', - year: 2002, - by: 'The Economist' }, - { award: 'Officer of the Order of Canada', - year: 2007, - by: 'Canada' } - ] - } - }, - { upsert: true } - ) - - See also :ref:`Create with Upsert`. - - .. _crud-update-save: +If the ```` argument contains only field and value pairs, the +:method:`~db.collection.update()` method *replaces* the +existing document with the document in the ```` argument, +except for the ``_id`` field. + +The following operation queries the ``bios`` collection for the first +document that has a ``name`` field equal to ``{ first: 'John', last: +'McCarthy' }`` and replaces all but the ``_id`` field in the document +with the fields in the ```` argument: + +.. code-block:: javascript + + db.bios.update( + { name: { first: 'John', last: 'McCarthy' } }, + { name: { first: 'Ken', last: 'Iverson' }, + born: new Date('Dec 17, 1941'), + died: new Date('Oct 19, 2004'), + contribs: [ 'APL', 'J' ], + awards: [ + { award: 'Turing Award', + year: 1979, + by: 'ACM' }, + { award: 'Harry H. Goode Memorial Award', + year: 1975, + by: 'IEEE Computer Society' }, + { award: 'IBM Fellow', + year: 1970, + by: 'IBM' } + ] + } + ) + +Upsert +------ + +If you set the ``upsert`` option in the ```` argument to +``true`` or ``1`` and no existing document match the ```` +argument, the :method:`~db.collection.update()` method can +insert a new document into the collection. + +The following operation queries the ``bios`` collection for a document +with the ``_id`` field equal to ``11`` and the ``name`` field equal to +``{ first: 'James', last: 'Gosling'}``. If the query selects a +document, the operation performs an update operation. If a document is +not found, :method:`~db.collection.update()` inserts a new +document containing the fields and values from ```` argument +with the operations from the ```` argument applied. +[#upsert-update-operators]_ + +.. code-block:: javascript + + db.bios.update( + { _id:11, name: { first: 'James', last: 'Gosling' } }, + { + $set: { + born: new Date('May 19, 1955'), + contribs: [ 'Java' ], + awards: [ + { + award: 'The Economist Innovation Award', + year: 2002, + by: 'The Economist' + }, + { + award: 'Officer of the Order of Canada', + year: 2007, + by: 'Canada' + } + ] + } + }, + { upsert: true } + ) + +See also :ref:`Upsert ` in the +:doc:`/applications/create` section. .. [#upsert-update-operators] If the ```` argument includes only field and value pairs, the new document contains the fields and values specified in the ```` argument. If the ```` argument includes only :ref:`update - operators `, the new document contains the fields + operators `, the new document contains the fields and values from ```` argument with the operations from the ```` argument applied. +.. _crud-update-save: + Save ---- -The :method:`save() ` method updates an existing +The :method:`~db.collection.save()` method updates an existing document or inserts a document depending on the ``_id`` field of the -document. The :method:`save() ` method is -analogous to the :method:`update() ` method +document. The :method:`~db.collection.save()` method is +analogous to the :method:`~db.collection.update()` method with the ``upsert`` option and a ```` argument on the ``_id`` field. -The :method:`save() ` method has the +The :method:`~db.collection.save()` method has the following syntax: .. code-block:: javascript db.collection.save( ) -Consider the following examples of the :method:`save() -` method: - -- If the ```` argument contains the ``_id`` field that exists - in the collection, the :method:`save() ` method - performs an update that replaces the existing document with the - ```` argument. +Save Performs an Update +~~~~~~~~~~~~~~~~~~~~~~~ - The following operation queries the ``bios`` collection for a - document where the ``_id`` equals - ``ObjectId("507c4e138fada716c89d0014")`` and replaces the document - with the ```` argument: +If the ```` argument contains the ``_id`` field that exists +in the collection, the :method:`~db.collection.save()` method +performs an update that replaces the existing document with the +```` argument. - .. code-block:: javascript +The following operation queries the ``bios`` collection for a document +where the ``_id`` equals ``ObjectId("507c4e138fada716c89d0014")`` and +replaces the document with the ```` argument: - db.bios.save( - { - _id: ObjectId("507c4e138fada716c89d0014"), - name: { first: 'Martin', last: 'Odersky' }, - contribs: [ 'Scala' ] - } - ) - -- If no ``_id`` field exists or if the ``_id`` field exists but does - not match any document in the collection, the :method:`save() - ` method performs an insert. - - The following operation adds the ``_id`` field to the document, - assigns to the field a unique :term:`ObjectId`, and - inserts the document into the ``bios`` collection: +.. code-block:: javascript - .. code-block:: javascript + db.bios.save( + { + _id: ObjectId("507c4e138fada716c89d0014"), + name: { first: 'Martin', last: 'Odersky' }, + contribs: [ 'Scala' ] + } + ) - db.bios.save( - { - name: { first: 'Larry', last: 'Wall' }, - contribs: [ 'Perl' ] - } - ) +.. seealso:: :ref:`crud-create-insert-save` and + :ref:`crud-create-save` in the :doc:`/applications/create` section. - .. seealso:: :ref:`Create with Save `. +.. _crud-update-operators: Update Operators ----------------