pradeep
pradeep

Reputation: 35

count for a specific key within documents

My document structure looks like this:

{
  "_id" : ObjectId("4f6b0f6aaa294de8ff476bf3"),
  "BLOODGAS" : [{
      "ABG_PH" : 0.0, //<< one
      "XYZ" : 2.0,
      "PQR" : 3.0
    }]
}
{
  "BLOODGAS" : [{
      "ABG_PH" : 1.0, //<< two
      "XYZ" : 2.0,
      "PQR" : 3.0
    }, {
      "ABG_PH" : 0.0, //<< three
      "XYZ" : 1.0,
      "PQR" : 2.0
    }, {
      "ABG_PH" : 0.0, //<< four
      "XYZ" : 5.0,
      "PQR" : 6.0
    }],
  "_id" : ObjectId("4f6b0f11aa294de8ff476bf2")
}

Now based on the current structure I have completely four instances with the key ABG_PH

But with the following query I get a count : 2

db.myCollection.find({ "BLOODGAS.ABG_PH" : 0 }).count();

I should get a count 3, since I have 3 instances of ABG_PH with the value 0.

What kind of query would I need to get a count of 3 with the above data.

Update : If this isn't possible with a straightforward query, could I use map reduce here?

Upvotes: 0

Views: 268

Answers (2)

Nic Cottrell
Nic Cottrell

Reputation: 9685

If you're still in the early stages of development, you might want to consider using the 2.1 dev version of Mongo which has a new aggregation framework. I believe for this example you would $unwind the BLOODGAS array and then group and count.

This feature will be in the next stable 2.2 release.

Upvotes: 1

theAndroid
theAndroid

Reputation: 854

Actually, you have 2 documents in your collection, each of them embedding relating data (BLOODGAS array). When you query the collection, you try to count the numbers of documents which embedded data match your query, not the number of related BLOODGAS. You must split BLOODGAS into a dedicated collection to count that way :( or parse the arrays in your development language or platform. But you can not consider BLOODGAS as documents.

Upvotes: 1

Related Questions