user14361300
user14361300

Reputation:

How to count the number of documents with the specified field in MongoDB?

Consider the below documents in a collection "project"

{
  _id:"1",
  "project_id":"1",
  "Name":"A",
  "type":"Description"
}

{
  _id:"2",
  "Name":"A",
  "project_id":"2",
  "type":"Paragraph"
}

{
  _id:"3",
  "Name":"A",
  "project_id":"1",
  "type":"Description"
}

{
  _id:"4",
  "Name":"A",
  "project_id":"3",
  "type":"Description"
}

I want to write a mongodb query where it has to count the number of documents with "type":"Description" for the "project_id":"1".

Upvotes: 0

Views: 2568

Answers (1)

Tiya Jose
Tiya Jose

Reputation: 1419

You can find the count by using any of the following methods:

  1. Using db.collection.countDocuments(query, options)
db.collection.countDocuments({ "project_id": "1","type":"Description"})

It performs an aggregation of the document to return an accurate count

  1. Using db.collection.count(query, options)
db.collection.count({ "project_id": "1","type": "Description" })

Avoid using the db.collection.count() method without a query predicate since without the query predicate, the method returns results based on the collection’s metadata, which may result in an approximate count.

  1. Using aggregation pipeline stage $count
db.collection.aggregate([
  {
    $match: {
      "project_id": "1",
      "type": "Description"
    }
  },
  {
    $count: "count"
  }
])

MongoDB Query

PS: Replace the "collection" with your collection name.

Upvotes: 1

Related Questions