Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb Query - Count + where condition

I have a mongodb collection which has collection with a tag and date field.

I want to count the number of all tags which can be done by this query

db.collection.count( { tags: "abc" })

But I would like to get counts of all unique tags together. And I also want to put a where condition on the date, as in I want to query for a certain time period.

like image 257
Pi Horse Avatar asked Mar 30 '13 02:03

Pi Horse


People also ask

What is Count query in MongoDB?

Parameters with count query in MongoDB: count: <collection or view>: Count the collection or view documents. query: <document>: Query used to count of documents as per query specified. limit: <integer>: This is optional parameter of count method in MongoDB.

How to find MongoDB Records based on a condition?

Find MongoDB records based on a condition? To find MongoDB based on a condition, use find () and set the condition. Let us create a collection with documents −

What is the difference between and and or conditions in MongoDB?

The AND condition displays only those records where both condition 1 and condition 2 are met. The OR condition displays those records if any one of the conditions is met. The IN condition takes multiple values and based on these values, records are displayed. Prerequisites. MongoDB 4.4.0, MongoDB Setup. Sample Data

Can we use Index in a query in MongoDB?

If, however, the query can use an index but the query predicates do not access a single contiguous range of index keys or the query also contains conditions on fields outside the index, then in addition to using the index, MongoDB must also read the documents to return the count.


2 Answers

A very simple approach:

db.collection.distinct("tags", {dateField: {$gt: dateValue}}).forEach(function (tag) {
    var count = db.collection.count({"tags" : tag})
})
like image 133
Ori Dar Avatar answered Oct 07 '22 17:10

Ori Dar


You can use the mongoDD Aggregation framework for solving this problem (http://docs.mongodb.org/manual/applications/aggregation/) . In case you do not get everything done . you always a option to do it through map-reduce (http://docs.mongodb.org/manual/applications/map-reduce/) . I have used map-reduce to build my own search options for special requirement. So any point of time map-reduce will help you to do what you want to do which is not possible by simple query. I am not giving the query because I do not have much information how you want to get the data and how is your collection looks like but both the two option will help you to get it very easily.

like image 33
Devesh Avatar answered Oct 07 '22 16:10

Devesh