MongoDB: How to recover the array that contains a specific value?


If I have this schema:

user={ email:String,things:[],rules:[{name:String,devicesInvolved:[]} ]

I do not manage to retrieve all the users and rules, that contains a specific device involved in a rule. For example, I want to retrieve all the users that in their rules, in their devices involved, contains a specific device.

Use positional operator $ to project just the matching element from the array

db.user.find({'rules.devicesInvolved':'device1'}, {email:1, 'rules.$':1})


Above query will return only the first match. If you want all matching elements from the array then better use aggregates

  {$unwind: '$rules'},
  {$match: {'rules.devicesInvolved': 'device1'}},
  {$group: {_id: '$_id', rules: {$addToSet: '$rules'}}}