1

I have two questions. I found similar things but I couldn't adapt to my problem.

query = {'$and': [{'cpc.class': u'24'},
                  {'cpc.section': u'A'},
                  {'cpc.subclass': u'C'}]}

collection:

       {"_id":1, 
        "cpc": 
         [{u'class': u'24',
          u'section': u'A',
          u'subclass': u'B'}, 
        {u'class': u'07',
          u'section': u'C',
          u'subclass': u'C'},]}
       {"_id":2, 
        "cpc": 
         [{u'class': u'24',
          u'section': u'A',
          u'subclass': u'C'}, 
        {u'class': u'07',
          u'section': u'K',
          u'subclass': u'L'},]}

In this query, two documents will be fetched.

1) But I want to fetch only the second document ("_id": 2) because it matches the query exactly. That is, the second document contains a cpc element which its class equals to 24, its section equals to A, and its subclass equals to C.

2) And I want to fetch only the matching element of cpc if possible? Otherwise I have to traverse all elements of each retrieved documents; if I traverse and try to find out which element matches exactly then my first question would be meaningless.

Thanks!

1 Answer 1

1

1) you're looking for the $elemMatch operator which compares subdocuments as a whole and is more concise then separate subelement queries (you don't need the $and in your query by the way):

query = { 'cpc' : { 
               '$elemMatch': { 'class': u'24',
                                'section': u'A',
                                'subclass': u'C' } } };

2) That can be done using a projection:

db.find(query, { "cpc.$" : 1 })

The $ projection operator documentation contains pretty much this use case as an example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.