0

Say I have 3 documents:

[
  {
    name: "Phil",
    auth: true,
    sources: [
      {
        user: '123',
        area: 'PA'
      },{
        user: '456',
        area: 'NYC'
      }
    ]
  },{
    name: "Chris",
    auth: true,
    sources: [
      {
        user: '123',
        area: 'SF'
      }
    ]
  },{
    name: "Joel",
    auth: true,
    sources: [
      {
        user: '456',
        area: 'LA'
      }
    ]
  }
]

My desired query is as follows:

  1. Find all documents where auth: true (all 3).
  2. Then I only want to return the "sources" where user: 123.

That is to say, I want to return the ENTIRE document where Auth is true, but within those documents I only want to return the sources where the "user" is "123".

Something like db.users.find({auth:true, 'sources.user': '123'}) obviously returns whole documents with a matchingsource.user`. I need something like:

  db.users.find({auth:true}, {'source.user: "123"': 1}) 

or the like. Perhaps this can be done with map reduce? Any ideas?

JVG
  • 20,198
  • 47
  • 132
  • 210
  • Good call @BlakesSeven, this answer in particular got me what I wanted http://stackoverflow.com/a/12241733/556006 – JVG Oct 08 '15 at 07:36
  • There are several takes on this right from matching a single array element to multiple. There are several examples there showing varying methods for various approaches, so it's really just a matter of which one suits best. But also the point here is the "big blue button" you should be seeing with the message along the lines of "this answers my question" that you should be clicking on to self confirm the duplcate question. Whether it is the accepted answer or not that helped is not the point. – Blakes Seven Oct 08 '15 at 08:05

0 Answers0