Pi Horse
Pi Horse

Reputation: 2430

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.

Upvotes: 5

Views: 11076

Answers (5)

veritas
veritas

Reputation: 432

db.note.find({clientID:115, noteType:"CLINICALNOTE", noteID:{$gte:655393}}).count()

e.g . find remaining notes to process of client 115 if current note is 655393

Find all notes from note collection where client is 115 and noteType is Clinical and noteID is greater than 655,393.

This may give the result as e.g 160,111 i.e these many notes left to process

Upvotes: 0

MAX RAMIREZ
MAX RAMIREZ

Reputation: 17

db.collection.aggregate([
   {"$group" : {_id:"$tags", count:{$sum:1}}}, {$sort:{"count":-1}}
])

Upvotes: 1

Hasan
Hasan

Reputation: 161

You should use a combination of find and count

db.collection.find({condition}).count

Upvotes: 1

Ori Dar
Ori Dar

Reputation: 19000

A very simple approach:

db.collection.distinct("tags", {dateField: {$gt: dateValue}}).forEach(function (tag) {
    var count = db.collection.count({"tags" : tag})
})

Upvotes: 4

Devesh
Devesh

Reputation: 4550

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.

Upvotes: 1

Related Questions