1

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!

2
  • What should be the expected output? Commented Sep 21, 2018 at 17:35
  • Simply a set of documents from the users-collection where the email has been verified. Commented Sep 21, 2018 at 17:54

2 Answers 2

1

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]}}}
])
Sign up to request clarification or add additional context in comments.

Comments

0

something like this should work:

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

1 Comment

$in only takes arrays and can't interpret them from strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.