Reputation:
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
Reputation: 1419
You can find the count by using any of the following methods:
db.collection.countDocuments({ "project_id": "1","type":"Description"})
It performs an aggregation of the document to return an accurate count
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.
db.collection.aggregate([
{
$match: {
"project_id": "1",
"type": "Description"
}
},
{
$count: "count"
}
])
PS: Replace the "collection" with your collection name.
Upvotes: 1