When searching sub documents there are times when it is ideal to select individual fields based on your matching clause. When MongoDB does a query with a match and field selection it seems to drop the matching clause when handling the field selection. To help detail what I am talking about, assume you have the following:
{ "_id" : ObjectId("4dcebcb7441737b80c5db656"), "hash" : "123456", "contents" : [
,
{ "user" : "dixon", "flags" : [ ] }] }
This document is pretty straight forward to understand. What I want to extract from this document is the "flags" portion for a given user. To do this I put together the following query:
> db.tmp1.find(
{'hash':'123456','contents.user':'brandon'},
{'contents.flags':1})
You can see here that I am matching based on the what would be unique hash, and the user with the value of brandon. In this case I am selecting the flags field as the only output to show on the results. The following is what I get:
{ "_id" : ObjectId("4dcebcb7441737b80c5db656"), "contents" : [
{ "flags" : [ "checked" ] },
{ "flags" : [ ] }] }
As you can see here, I got my flags that I wanted, but I also picked up the flags field from the "dixon" user. This is not the expected result of the query as my matching clause only said to match those with the user "brandon". It appears that MongoDB only uses the match clauses when doing the initial search, but it does not apply them to the selected output fields.
- duplicates
-
SERVER-828 Support for selecting array elements in return specifier (projection)
- Closed