Alexander Makarov
Alexander Makarov

Reputation: 165

MongoDB indexing and counting for subdocument

Please give me an advise, how i can resolve my issue. I have a MongoDB collection "cards" with over 5 million documents. Here is example of typycal document in my collection

 {
        "_id" : "300465-905543",
        "products" : "00000",
        "groupQuality" : {
                "defQuality" : 100,
                "summQuality" : 92.22
        }
}

I need count up quantity of documents with some products and with some value of quality so i tried to use something like this

db.cards.count({groupQuality.defQuality : {$gt : 50, $lte : 100}})

For improving speed of this operation i created index {groupQuality.defQuality : 1} It was good decision, count of documents returned fast, but after adding into imbedded document with name "groupQuality" one more group of quality i must create another index for this group. Quantity of new groups of quality may be huge, so i don't want build index for every new group of quality. I start thinking about creating index {groupQuality : 1} which will cower all groups of quality in imbedded document. Does it possible in MongoDB? If i can create such index, how can i make a query to count up documents with some products and with some value of quality in case using index by groupQuality? I tryed next query but it always return 0.

db.cards.count({ products : "00000", groupQuality : { defQuality : {$gt : 50, $lte : 100}, summQuality : {$gt : 0, $lte : 100}}})

Where is my mistake?

Upvotes: 0

Views: 82

Answers (1)

Philipp
Philipp

Reputation: 69703

When you have nested fields, you need to provide the full path for every field you match instead of providing a nested document:

db.cards.count({ 
      "products" : "00000", 
      "groupQuality.defQuality" : {$gt : 50, $lte : 100}, 
      "groupQuality.summQuality" : {$gt : 0, $lte : 100}
})

Upvotes: 1

Related Questions