Performing Select or Find Queries in MongoDB: A Comprehensive Guide


Select or Find query

To retrieve the first record (document) from a collection in MongoDB, you can use the findOne() method. Here's how you can do it.

db.collectionName.findOne()

Assuming you have a collection named "student," you can retrieve the first document from it like this

db.students.findOne()

Output

First Record

Keep in mind that the order of documents in MongoDB is not guaranteed unless you have explicitly sorted them in a specific order. If you need a specific document to be first, you should apply sorting or filtering criteria to your query to ensure the desired result.

Show or Select a particular Collection

In MongoDB, to select or show the contents of a particular collection, you can use the db.collectionName.find() command in the MongoDB. Here's how you can do it:

db.collectionName.find()

Once you are in the correct database, you can use the db.collectionName.find() command to select or show the contents of the desired collection. Replace "collectionName" with the name of the collection you want to work with

db.students.find()

Output

All Record

Count of Field or Record in Particular Collection

To count the number of documents (records) in a particular collection in MongoDB, you can use the countDocuments() method. Here's how you can do it

db.collectionName.find().count()

Assuming you have a collection named "students," you can count the documents in it like this:

db.students.find().count()

Output

Count Records

To find a Particular Field in Collection

To find a particular field in a collection in MongoDB, you can use the find() method and specify the field you want to retrieve in the projection. Here's how you can do it

db.mycollection.find({}, { fieldName: value })

If you want to filter or query specific documents within the collection, you can provide query criteria as an argument to the find() method. For example, to find documents where the "Name" field is "Sam," you can do

db.students.find({"Name":"Sam"})

Output

Specific Field Record

Using Count for Particular Field

If you want to count the occurrences of a particular field for documents that match specific criteria in MongoDB, you can use the count() method along with a query. Here's how you can do it

db.collectionName.find({"feildName"}).count()

Assuming you have a collection named "students," and you want to count the occurrences of the "fieldName" field for documents where a certain condition is met:

db.students.find({"Name":"Sam"}).count()

Output

Count Specific Field Record

Using Limit

In MongoDB, you can use the limit() method to limit the number of documents returned by a query. This is especially useful when you want to retrieve only a specific number of documents from a collection. Here's how to use limit()

db.collectionName.find(query, projection).limit(limitValue)
  • collectionName: Replace this with the name of your collection.
  • query: Optional. You can specify query conditions here to filter the documents you want to retrieve. If you don't specify a query, it will match all documents in the collection.
  • projection: Optional. You can specify which fields you want to include or exclude from the result documents. If you don't specify a projection, it will include all fields.
  • limitValue: The number of documents to limit the query results to.

Select first 2 or more records (Ascending Order)

db.students.find().limit(2)

Output

Limit

Select first 2 or more records (Descending Order)

db.students.find().limit(-2)

Keep in mind that the limit() method is typically used for pagination or to limit the number of results when you don't want to retrieve the entire collection. It should be used in combination with other query operators to achieve more complex filtering and sorting if needed.

Sort

In MongoDB, the sort() method is used to sort the documents in a collection based on one or more fields. You can use sort() to arrange the documents in either ascending (ascending order) or descending (descending order) fashion. Here's how to use sort().

db.collectionName.find(query).sort(sortSpecification)
  • collectionName: Replace this with the name of your collection.
  • query: Optional. You can specify query conditions here to filter the documents you want to retrieve. If you don't specify a query, it will match all documents in the collection.
  • sortSpecification: An object that specifies the fields by which you want to sort and the sorting order. It should be in the format { fieldName: sortOrder }, where fieldName is the name of the field to sort by, and sortOrder can be 1 for ascending or -1 for descending.

Ascending Order

Sort documents in the "students" collection in ascending order based on the "Name" field.

db.students.find().sort({"Name":1})

Output

Sort

Descending Order

Sort documents based on multiple fields. For example, sort by "name" in descending order.

db.students.find().sort({"Name":-1})

Output

Sort

Show and Hide a Particular Field in Collections

In MongoDB, you can control which fields are shown or hidden (excluded) in query results using the projection feature. You can use the find() method with projection to specify which fields you want to include or exclude. Here's how you can show and hide a particular field in collections

db.collectionName.find({"condition"},{"feildName":value})

Show a Particular Field

To show a particular field, include the field you want to display in the projection.For example, if you have a collection named "students" and you want to show the "name" and "gender" field.

db.students.find({"Gender":"Male"},{"Gender":1,"Name":1,"_id":0})

In this example, { gender:1, name: 1, _id: 0 } is the projection. It includes the "name" and "gender" field (1 indicates inclusion), and it excludes the "_id" field (0 indicates exclusion). The "_id" field is automatically included unless explicitly excluded.

Hide a Particular Field

To hide a particular field, simply exclude it from the projection. For example, if you want to hide the "id" field in the query results

db.students.find({"Gender":"Male"},{"Gender":1,"Name":1,"_id":0})

In this example, { id: 0 } is the projection, and it excludes the "id" field from the query results.

Output

Hide and Show

You can customize the projection to include or exclude multiple fields based on your requirements.

Distinct

In MongoDB, the distinct() method is used to retrieve distinct values (unique values) from a specified field in a collection. It is often used when you want to find unique values within a specific field, such as finding all unique categories in a collection.

Here's the basic syntax for using distinct():

db.collectionName.distinct(fieldName, query)
  • collectionName: Replace this with the name of your collection.
  • fieldName: Specify the field from which you want to retrieve distinct values.
  • query: Optional. You can provide a query to filter the documents before finding distinct values. This is useful when you want to find distinct values only among a subset of documents.

Data

[
    {
        "Name":"Mano Bala",
        "Age":25,
        "Blood_Group":"B+",
        "Gender":"Male",
        "Pressure_Level":"140/100mmHg"
    },
    {
        "Name":"Renuka",
        "Age":27,
        "Blood_Group":"O-",
        "Gender":"Female",
        "Pressure_Level":"110/90mmHg"
    },
    {
        "Name":"Menaga",
        "Age":26,
        "Blood_Group":"AB-",
        "Gender":"Female",
        "Pressure_Level":"130/100mmHg"
    },
    {
        "Name":"Jaanu",
        "Age":23,
        "Blood_Group":"A+",
        "Gender":"Female",
        "Pressure_Level":"120/80mmHg"
    }
]
db.user.distinct("Blood_Group",{"Gender":"Female"})

The code you provided is a MongoDB query that uses the distinct() method to find distinct values in the "Blood_Group" field for documents where the "Gender" field is "Female" in the "user" collection. Let's break down the code step by step

  • db.user: This part specifies the collection you are querying. In this case, it's the "user" collection
  • distinct("Blood_Group", {"Gender": "Female"}) This is the distinct() method call, and it has two arguments:
    1. "Blood_Group": This argument specifies the field for which you want to find distinct values. In this case, you want to find distinct values in the "Blood_Group" field.
    2. {"Gender": "Female"}: This argument is a query filter that restricts the documents considered for finding distinct values. It means you only want to find distinct "Blood_Group" values for documents where the "Gender" field is equal to "Female."

The result of this query will be an array containing the unique "Blood_Group" values from the documents that meet the specified filter criteria.

Field Only

The code db.user.distinct("Blood_Group") is a MongoDB query that uses the distinct() method to retrieve distinct values from the "Blood_Group" field in the "user" collection.

db.user.distinct("Blood_Group")

Output

Distinct
  • db.user: This part specifies the collection you are querying, which is the "user" collection in this case.
  • .distinct("Blood_Group"): This is the distinct() method call, and it has one argument:
    • "Blood_Group": This argument specifies the field for which you want to find distinct values, in this case, "Blood_Group."

When you run this query, MongoDB will return an array containing all the unique values found in the "Blood_Group" field across all documents in the "user" collection.

This can be useful when you want to obtain a list of unique values from a specific field within a collection, which can be helpful for analysis or generating summary information.

Skip

In MongoDB, you can use the skip() method in conjunction with the find() method to skip a specified number of documents and retrieve documents starting from a particular position in the result set. This is often used for pagination or to skip a certain number of documents before fetching the next set of results. Here's how to use it

The basic syntax for using skip() is as follows:

db.collectionName.find(query).skip(numberOfDocumentsToSkip)
  • collectionName: Replace this with the name of your collection.
  • query: Optional. You can specify query conditions here to filter the documents you want to retrieve. If you don't specify a query, it will match all documents in the collection.
  • numberOfDocumentsToSkip: The number of documents to skip in the result set before starting to fetch documents.

Data

[
    {
      "name": "Sundar",
      "hobbies": [
        {
          "title": "Sports",
          "frequency": 3
        },
        {
          "title": "Cooking",
          "frequency": 6
        }
      ],
      "phone": 131782734
    },
    {
      "name": "Kumar",
      "hobbies": [
        {
          "title": "Cooking",
          "frequency": 5
        },
        {
          "title": "Cars",
          "frequency": 2
        }
      ],
      "phone": "012177972",
      "age": 30
    },
    {
      "name": "Sra",
      "hobbies": [
        {
          "title": "Sports",
          "frequency": 2
        },
        {
          "title": "Yoga",
          "frequency": 3
        }
      ],
      "phone": "8958785858",
      "age": null
    },
    {
      "name": "Raja",
      "hobbies": ["Sports", "Cooking", "Hiking"]
    }
]
db.user.find().skip(2)

Output

Skip

The code db.user.find().skip(2) is a MongoDB query that retrieves documents from the "user" collection but skips the first two documents in the result set.

  • db.user: This part specifies the collection you are querying, which is the "user" collection in this case.
  • .find(): This is the find() method used to query the collection. In this example, it retrieves all documents in the collection without any specific filtering criteria (i.e., it matches all documents).
  • .skip(2): This is the skip() method, which specifies that you want to skip the first 2 documents in the result set.

When you run this query, MongoDB will retrieve all documents in the "user" collection but exclude the first two documents from the result. The result will include all documents starting from the third document onwards.

This can be useful for scenarios where you want to implement pagination or retrieve a subset of documents from a larger collection.

Check Key Exists or not

In MongoDB, you can check if a specific field exists in a document using various query operators and methods. Here are some common approaches to check if a key (field) exists in a document

db.collectionName.find({"feildName":{$exists:true or false}})

Using the $exists Operator

You can use the $exists operator within a query to check if a field exists in a document. It returns documents where the specified field either exists (true) or does not exist (false). For example: if true

db.user.find({"Name":{$exists:true}})

Output

Exists

if false

db.user.find({"Name":{$exists:false}})

Output

Exists