Basic MongoDB CRUD

From Knowledge Kitchen
Jump to navigation Jump to search


The MongoDB find() method takes two arguments:

  • criteria - the conditions that identify which documents should be returned by the query
    • equivalent to the WHERE clause in SQL
  • projection - limits which fields from the documents matching the criteria are returned by the database
    • equivalent to the list of field names in SQL statements


Example data set

The examples here assume a collection named books has been added to a MongoDB database.

MongoDB read examples

No criteria

Example of calling the find() method with no arguments:

  • this query is being run on the books collection
  • the method call indicates no criteria, so there are no limits on what it selects
  • ... so it selects all documents in the books collection


db.books.find()

One criterion

Example of calling the find() method with one criterion:

  • Criteria are specified as JSON objects.
  • the criterion indicates to select only those books where the author field has the value "Leo Tolstoy"
db.books.find( 
	{
		"author": "Leo Tolstoy"
	} 
)

One criterion with an operator

Example of calling the find() method with a criterion including an operator:

  • this query will find any books over $25
  • notice the use of the conditional operator $gt
db.books.find( 
	{ 
		"price": { 
			$gt: 25 
		} 
	} 
)

Two criteria

Example of calling the find() method with two criteria, one of which includes comparison operators.

  • Note that and is implicit in the syntax of the price criterion
    • there is an explicit $and operator that could have been used instead, but it wasn't necessary based on how we wrote the query in this example

The following query returns books published by Penguin in the price range of $10-$20. Notice the use of a projection to indicate that we do not want the _id value returned.

db.books.find( 
	{
		"price": {
			$gte: 10, 
			$lte: 20
		}, 
		"edition": "Penguin"
	}, 
	{
		"_id": 0 
	}
)

One criterion using the $or operator

Example of using the $or operator:

  • note that or logic has to be explicitly indicated by the $or operator
  • the syntax for the and operator follows the same pattern

The following query finds books where the price is >= $20 or the publisher is Penguin:

db.books.find(
	{ 
		$or: [  
			{
				"price": {
					$gte : 20
				}
			}, 
			{
				"edition": "Penguin"
			} 
		] 
	}
) 

The count() method

The count() method can be used to count results returned by any read.

Counting documents

The following two statements are functionally equivalent. They both return how many documents are in the books collection:

db.books.find().count()
db.books.count()

Counting documents with a criterion

This example returns a count of all the books published by Penguin in the books collection

db.books.find(
	{
		"edition": "Penguin"
	}
).count()

Another way to perform the same query:

db.books.count(
	{
		"edition": "Penguin"
	}
) 

Operators

Comparision operators

The full set of comparison operators:

  • $gt - greater than
  • $gte - greater than or equal to
  • $lt - less than
  • $lte - less than or equal to

All comparison operators follow the same general syntactical pattern, as seen through the examples on this page.


$eq

Determines whether a given field is equal to a specific value.

The following query finds all books where the year_written is 1985

db.books.find(
	{
		"year_written": {
			$eq: 1985
		} 
	}
)

Note that this is functionally equivalent to the following example which doesn't expicitly use the $eq operator:

db.books.find(
	{ 
		"year_written": 1985 
	}
)

$ne

Determines whether a given field is NOT equal to a specific value.

The following query finds all books where the year_written is not 1985

db.books.find(
	{
		"year_written": {
			$ne: 1985
		} 
	}
)

Logic operators

$and

Performs standard boolean AND logic between two statements:

  • note that there is an implicit AND logic when specifying multiple criteria, so this operator is sometimes redundant.
  • read the official documentation

The following query finds books published by Penguin that were written before 1985:

db.books.find(
	{ 
		$and: [ 
			{
				"edition": "Penguin"
			}, 
			{
				"year_written": {
					$lt: 1985
				}
			} 
		] 
	}
) 

$or

Performs standard boolean OR logic between two statements:

The following query finds books that either cost more than $15 or were written after the turn of the 20th century:

db.books.find(
	{ 
		$or: [ 
			{
				"price": {
					$gte: 15
				}
			}, 
			{
				"year_written": {
					$gte: 1900
				}
			}
		]
	}
)

$in

Determines whether the value in given field is one of the elements in a given array of values:

The following query finds books where the year_written is either 1865 or 1925:

db.books.find(
	{ 
		"year_written": { 
			$in: [ 1865, 1925 ]
		}
	}
) 

$nin

Determines whether the value in a given field is NOT one of the elements in a given array of values:

The following query returns all books that were not written in 1865, 1925, 1927, 1802, 1814, or 1999:

db.books.find(
	{ 
		"year_written": { 
			$nin: [ 1865, 1925, 1927, 1802, 1814, 1999 ]
		} 
	}
)

Creating, updating, and deleting documents

Just as in relational databases with rows, it is possible to create, update, and delete documents in MongoDB

Create new documents

To create a new document representing a book, use the insert() method, and specify all fields:

db.books.insert(
   {
		"title": "Pattern Recognition",
		"author": "William Gibson",
		"year_written": 2003,
		"edition": "Penguin",
		"price": 14.99
   }
)

Update documents

To update existing documents, use the update() method

For example, to sell all books published before this millennium for only $5.99, call the update method with the following arguments:

  • the first argument specifies the criteria indicating which documents to update
  • the second argument represents the fields to be changed and their new values
  • the third argument indicates to apply this to all rows that match the criteria
db.books.update(
   { "year_written": { $lt: 2000 } },
   { $set: { "price": 5.99 } },
   { "multi": true }
)

Delete documents

To delete existing documents, use the remove() method.

  • the argument set the criteria indicating which documents to delete
db.books.remove(
   { 
   	"author": "William Gibson",
   	"title": "Pattern Recognition"
   }
)


What links here