MongoDB Collection Methods (Day 11)

Before reading this article, I highly recommend reading the following previous parts of the series:

MongoDB provides various methods for query and data manipulation. MongoDB supports the following collection methods for query and data manipulation.

Method_Name Description
Insert Create a new document
Remove Delete documents from collection
Update Modify documents in collection
Find Select a document from the collection and return a cursor object
Count Return a count of numbers of documents in a collection
Distinct Return array of document that have distinct values
Findone Execute a query and return a single document
Save Replace existing document with a new document

Insert, Update, Remove and Find are the four methods we have already covered. You can learn how these methods work from previous parts of the series. Today we will cover the remaining methods.

First we create a collection with the following:

  1. db.createCollection("Post",{capped:false,autoIndexID:false,size:5040320,max:50})  
Now insert the following data into the “Post” Collection.
  1. {    "_id" : ObjectId("55c547eaacae58b1a7d7dff7"),  
  2.         "PostBY" : "Pankaj choudhary",  
  3.         "Time" : ISODate("2015-08-08T00:06:02.191Z"),  
  4.         "Title" : "Introduction of MongoDB",  
  5.         "Tags" : [  
  6.                 "NoSQL",  
  7.                 "MongoDB",  
  8.                 "Database"  
  9.         ],  
  10.         "Likes" : 4,  
  11.           
  12.         }  
  13.   
  14.   
  15.     {    "_id" : ObjectId("55c547feacae58b1a7d7dff8"),  
  16.         "PostBY" : "Pankaj choudhary",  
  17.         "Time" : ISODate("2015-08-08T00:06:22.805Z"),  
  18.         "Title" : "MongoDB Day1",  
  19.         "Tags" : [  
  20.                 "NoSQL",  
  21.                 "MongoDB",  
  22.                 "Database"  
  23.         ],  
  24.         "Likes" : 5,  
  25.           
  26.   
  27.     }  
  28. {  
  29.          "_id" : ObjectId("55c5480cacae58b1a7d7dff9"),  
  30.          "PostBY" : "Pankaj choudhary",  
  31.          "Time" : ISODate("2015-08-08T00:06:36.452Z"),  
  32.          "Title" : "MongoDB Day2",  
  33.          "Tags" : [  
  34.                  "NoSQL",  
  35.                  "MongoDB",  
  36.                  "Database",  
  37.                  "SQL"  
  38.          ],  
  39.          "Likes" : 3,  
  40.            
  41.  }  
  42.  {  
  43.          "_id" : ObjectId("55c5481bacae58b1a7d7dffa"),  
  44.          "PostBY" : "Pankaj choudhary",  
  45.          "Time" : ISODate("2015-08-08T00:06:51.436Z"),  
  46.          "Title" : "MongoDB Day3",  
  47.          "Tags" : [  
  48.                  "NoSQL",  
  49.                  "MongoDB",  
  50.                  "Database"  
  51.          ],  
  52.          "Likes" : 6,  
  53.            
  54.   
  55. }  
After inserting the data above, the data structure of the collection looks like below:



We will use this “Post” collection in all the examples.

count() Method

The count() method returns the number of documents that match the find() query. The find() method searches documents and returns a cursor object whereas the count method returns the number of results that match a query.

Syntax

  1. db.Collection_Name.count( <query>)  
Parameters

Parameter Type Description
Query Document Define the selection criteria

Count all documents

To count all the documents of a collection, use the count method without any selection criteria (query).

Example

  1. db.Post.count()  
This query counts all the documents of the “Post” collection and returns the number of documents.

Output

4

Count all Documents that match the selection criteria

To count the documents that match a specific selection criteria, use the <query> option in the count() method.

Example 1
  1. db.Post.count({Likes:{$gt:4}}) 
This query returns the number of posts that get more than 4 likes.

Output

2

Example 2
  1. db.Post.count({Likes:{$gt:5},Tags:"NoSQL"})  
This query returns the number of posts that get more than 5 likes and the “Tags” array contains the “NoSQL” value.

Output

1

Note

The db.collection.count(<query>) method is equivalent to db.collection.find(<query>).count(). Let's see an example.

Example 1
  1. db.Post.count()  
Output

4
  1. db.Post.find().count()  
Output

4

Example 2
  1. db.Post.count({Likes:{$gt:5},Tags:"NoSQL"})  
Output

1
  1. db.Post.find({Likes:{$gt:5},Tags:"NoSQL"}).count()  
Output

1

Distinct() Method

The Distinct() method finds the distinct values for a specified field and returns the results in an array for a single collection. The returned result must not be larger than the maximum BSON size.

Syntax
  1. db.Collection_Name.distinct(<field>,<query>)  
Parameters

Parameter Type Description
Field String The field for which to return distinct values.
Query Document Specify the document selection criteria

Return distinct value for a field

To return the distinct value from a field, use the “Field” parameter of the distinct method.

Example

db.Post.distinct("Tags")

This query returns the distinct value from the “Tags” array field.

Output

[ "Database", "MongoDB", "NoSQL", "SQL" ]

Return distinct value for fields that match the selection criteria

To return the distinct value from a field that matches a specific selection criteria, use the <query> option in the distinct() method.

Example

  1. db.Post.distinct("Tags",{Likes:{$gt:5}})  
This query returns the distinct value from the “Tags” field of documents where the value of the “Likes” field is greater than 5.

Output

[ "Database", "MongoDB", "NoSQL" ]

Note

If the value of a specific field is an array, then the distinct() method considers each value as a separate value. In other words, the [“Name”] and “Name” values of a field are treated as separate values in the distinct method.

Let's see an example.
  1. {  
  2.          "_id" : ObjectId("56c5298bacae58b1a7d7dffa"),  
  3.          "PostBY" : "Pankaj choudhary",  
  4.          "Time" : ISODate("2015-08-08T00:06:51.436Z"),  
  5.          "Title" : "MongoDB Day5",  
  6.          "Tags" : [  
  7.                  ["NoSQL"],  
  8.                  "NoSQL",  
  9.                  "MongoDB"  
  10.          ],  
  11.          "Likes" : 9  
  12.  }  
Now we will use the distinct() method for the “Tags” array and examine the result.

Query
  1. db.Post.distinct("Tags",{Likes:9})  
Output

[ "MongoDB", "NoSQL", [ "NoSQL" ] ]


findOne() Method

The findOne() method is used to return a document that satisfies the specified selection criteria. If more than one document matches the selection criteria, then the first document will return a value that reflects the order of documents on the disk.

Syntax
  1. db.Collection_Name.findOne(<query>,<projection>)  
Parameters

Parameter Type Description
Query Document Specify selection criteria
Projection Document Specify the field that the findOne method will return. I or true for include and 0 or false to exclude the field


Return single document

To return the single document without any selection criteria, use the findOne method without the <query> parameter.

Example

db.Post.findOne()

This query returns the first document from the collection.

Output

  1. {  
  2.          "_id" : ObjectId("55c547eaacae58b1a7d7dff7"),  
  3.          "PostBY" : "Pankaj choudhary",  
  4.          "Time" : ISODate("2015-08-08T00:06:02.191Z"),  
  5.          "Title" : "Introduction of MongoDB",  
  6.          "Tags" : [  
  7.                  "NoSQL",  
  8.                  "MongoDB",  
  9.                  "Database"  
  10.          ],  
  11.          "Likes" : 4  
  12.  }  
findOne() method with selection criteria

To determine the first document that matches a specified selection criteria, use the <query> parameter in the findOne() method.

Example
  1. db.Post.findOne({"Likes":{$gt:5}})  
This query returns the first document in which the value of the “Likes” field is greater than 5.

Output
  1. {  
  2.          "_id" : ObjectId("55c5481bacae58b1a7d7dffa"),  
  3.          "PostBY" : "Pankaj choudhary",  
  4.          "Time" : ISODate("2015-08-08T00:06:51.436Z"),  
  5.          "Title" : "MongoDB Day3",  
  6.          "Tags" : [  
  7.                  "NoSQL",  
  8.                  "MongoDB",  
  9.                  "Database"  
  10.          ],  
  11.          "Likes" : 6  
  12.  }  
Return specific field

To return the specific field from the document, use the <projection> parameter in the findOne() method.

Example
  1. db.Post.findOne({"Likes":{$gt:5}},{_id:0,Title:1,Tags:1})  
This query returns the “Title” and “Tags” fields from first document that match the selection criteria.

Output
  1. {  
  2.          "Title" : "MongoDB Day3",  
  3.          "Tags" : [  
  4.                  "NoSQL",  
  5.                  "MongoDB",  
  6.                  "Database"  
  7.          ]  
  8.  }  
Note

We cannot apply cursor methods (hasNext, Next) to the result of findOne() because the findOne() method returns only a single document. If we try to use the cursor method then MongoDB will throw an error.

Example
  1. var ab=db.Post.findOne({"Likes":{$gt:5}},{_id:0,Title:1,Tags:1})   
  2. var mc=ab.hasNext()?ab.next():null  
Output

2015-08-12T22:35:20.220+0530 E QUERY TypeError: Object [object Object] has no method 'hasNext' at (shell):1:11

Save method

The Save method either replaces the existing document or inserts a new document. It depends upon the _id field of the document. If we don't provide the _id field, then the save() method calls the insert() method and inserts a new document.

Syntax
  1. db.Collection_Name.save(<document>)  
Parameters

Parameters Type Description
Document Document Specify document to save to the collection

Document without _id field

If we use a document without defining an _id field, then the save() method calls the insert() method and a new document will be inserted into the collection.

Example

  1. db.Post.save({Title:"MongoDB-Day11",Tage:["Collection Method"]})  
This query inserts a new document into the collection.

Now we will check the existence of the newly inserted document.
  1. db.Post.find({Title:"MongoDB-Day11"}).pretty()  
Output
  1. {  
  2.          "_id" : ObjectId("55cb830e732675a928bf2f48"),  
  3.          "Title" : "MongoDB-Day11",  
  4.          "Tage" : [  
  5.                  "Collection Method"  
  6.          ]  
  7.  }  
Document with _id field

If a document contains an _id field then the save() method is the equivalent of the update method with the upsert method set to true. In other words, if the document contains an _id field, then there are two possibilities.

Case 1: _id already exists.

If _id already exists, then the field of an existing document will replace the new document's field.

Example:

We use the document whose _id is ObjectId("55c5481bacae58b1a7d7dffa").
  1. {  
  2.   
  3.         "_id" : ObjectId("55c5481bacae58b1a7d7dffa"),  
  4.         "PostBY" : "Pankaj choudhary",  
  5.         "Time" : ISODate("2015-08-08T00:06:51.436Z"),  
  6.         "Title" : "MongoDB Day3",  
  7.         "Tags" : [  
  8.                 "NoSQL",  
  9.                 "MongoDB",  
  10.                 "Database"  
  11.         ],  
  12.         "Likes" : 6  
  13.   
  14. }  
Now, we execute the save method and retrieve the document.
  1. db.Post.save({"_id" : ObjectId("55c5481bacae58b1a7d7dffa"),PostBy:"Nitin Yadav",Title:"MongoD  
  2. B-Day6",Tage:["Collection Method"]})  
Document after replacing:

Query
  1. db.Post.find({"_id" : ObjectId("55c5481bacae58b1a7d7dffa")}).pretty()  
Output
  1. {  
  2.          "_id" : ObjectId("55c5481bacae58b1a7d7dffa"),  
  3.          "PostBy" : "Nitin Yadav",  
  4.          "Title" : "MongoDB-Day6",  
  5.          "Tage" : [  
  6.                  "Collection Method"  
  7.          ]  
  8.  }  
Case 2: _id doesn't exist

If _id does not already exist in the collection, then a new document will be inserted.

Example

First, we check that _id already exists.

Query
  1. db.Post.find({"_id":ObjectId("123456789abcdef123456789")}).pretty()  
When we execute the preceding query, we did not retrieve a document. In other words this _id does not exist.

Now we insert a new document using the save() method.
  1. db.Post.save({"_id" : ObjectId("123456789abcdef123456789"),PostBy:"Pradeep Yadav",Title:"Mong  
  2. oDB-Day7",Tags:["NoSQL","asp.Net"]})  
Now we check this document.

Query
  1. db.Post.find({"_id" : ObjectId("123456789abcdef123456789")}).pretty()  
Output
  1. {  
  2.          "_id" : ObjectId("123456789abcdef123456789"),  
  3.          "PostBy" : "Pradeep Yadav",  
  4.          "Title" : "MongoDB-Day7",  
  5.          "Tags" : [  
  6.                  "NoSQL",  
  7.                  "asp.Net"  
  8.          ]  
  9.  }  
The above result ensures that a new document is inserted into the “Post” collection.

Today we learned some collection methods. In the next article, I will explain a new topic. Until then keep coding and continue practicing.

Thanks for reading this article!
 
Author
Pankaj Kumar Choudhary
71 26.6k 13.4m
Next » MongoDB Cursor Methods (Day 12)