l'arbre
l'arbre

Reputation: 719

MongoDB - Select where array contains a document field

The documents in my collection("users") look like this:

{
    _id: ObjectID(...),
   verifiedFields:
   {
       email: ["[email protected]", "[email protected]"],
       phone: [...]
   },
   profiles:
   [
       {
           _id: ObjectID(...),
           fields: 
           {
                email: { value: "[email protected]" }
           }
       }
   ]
}

I would like to now select all users who's profiles.field.email.value is contained within their verifiedFields.email. I would like to avoid having to store a boolean verified as the user should be allowed to have multiple profiles with the same fields and this would cause complications later on. Thanks in advance!

Upvotes: 1

Views: 99

Answers (2)

galkin
galkin

Reputation: 5519

Your query is:

db.users.find({
  $expr: {$gt: [{$size: {$setIntersection: ['$profiles.fields.email.value', '$verifiedFields.email']}}, 0]}
})

This query doesn't use indexes, so on performance issue you will need add verified field.

Please, check aggregation pipeline and $expr for better understanding this query. Pipeline used for testing your query was:

db.test.aggregate([
  { $addFields: {a : '$profiles.fields.email.value'}},
  { $addFields: {b: { $setIntersection: ['$a', '$verifiedFields.email']}}},
  { $match: {$expr: {$gt: [{$size: '$b'}, 0]}}}
])

Upvotes: 1

Isaac Vidrine
Isaac Vidrine

Reputation: 1666

something like this should work:

collection('users').find({
    'profiles[0].fields.email.value': {$in: 'verifiedFields.email'}
})

Upvotes: 0

Related Questions