Only extract particular specific subfields that meet search criteria in MongoDB

时间:2015-07-31 20:23:26

标签: mongodb

I'm very new to using mongodb (as in, I've been using it for less than 4 hours), and relatively inexperienced with databases in general, so please forgive me if what I'm asking is completely n00bish or I'm getting the terminology wrong (please correct me on the terminology).

I know how to identify records where the 'name' subfield, nested within the 'events' sub-field, nested within 'states' is equal to "Level Start", e.g.

db.test.find({"states.events.name":"Level Start"})

but that returns the entire record (document?)

but when I perform that particular find, it returns every field, sub-field, etc for every record that meets that criteria. Instead, I only want to return the exact sub-fields matching the criteria (along with all sub-fields nested within said sub-field, matching the criteria) and not all the sub-fields that exist at the same level (i.e. something that I could do using using projections, iirc).

I'm have the vague notion that I can accomplish something like this using the elemMatch function but from the documentation it sounds like it will only retrieve the first matching sub field, and I know that within a given record/document there will be multiple instances of sub fields that match those criteria, and I need to grab all of them.

The 'best' idea I have so far (although I have no idea how to implement this), would be to somehow nest multiple searches within each other. First, identify all the records that match said criteria, then use projections to only output the contents of that record at the correct depth. The results of that search would then be fed into another search using the same criteria as before. This would turn what were previously sub-fields in the original document into documents themselves. And then I could simply do a search over this new set of documents to find what I want.

I'm not sure if that makes any sense, but hopefully someone will understand what I'm trying to do.

0 个答案:

没有答案