1

I'm trying to return only the subdocument that has a matching e-mail. I've done what the documentation says here, I believe. Here's what I'm trying:

function lookupReferral(email) {
    return getConnection().then(db => db.collection('Referrals').findOne(
        {
            emails: {$elemMatch: {name: email}}
        },
        {
            "emails.$": 1 
        }
    ));
}

Here's an example of a document (I cut down the emails array for brevity):

{
"_id": {
    "$oid": "5b65979d84b8942e04f4e346"
},
"accountCode": "auth0|5b4de18d8bed60110409ded5",
"accountEmail": "[email protected]",
"emails": [
    {
        "name": "[email protected]",
        "signedUp": false,
        "updated": {
            "$date": "2018-08-04T12:10:05.752Z"
        }
    },
    {
        "name": "[email protected]",
        "signedUp": false,
        "updated": {
            "$date": "2018-08-04T12:10:05.752Z"
        }
    }
],
"created": {
    "$date": "2018-08-04T12:10:05.985Z"
},
"updated": {
    "$date": "2018-08-04T12:10:05.985Z"
}

For some reason it returns null (meaning it doesn't exists I guess?), but if I remove what I specifically want, then I get the entire document returned.

2
  • db.collection('Referrals').findOne( { emails: { $elemMatch: { name: "[email protected]" }}}, { emails: { $elemMatch: { name: "[email protected]" }}} ) Try his Commented Aug 9, 2018 at 2:35
  • Nope, doesn't work. Still returns null when I use an e-mail that exists in a subdocument { emails: {$elemMatch: {name: "[email protected]"}}}, { emails {$elemMatch: {name: "[email protected]"}}} Commented Aug 9, 2018 at 9:43

1 Answer 1

1

You can try this

db.collection.find({
  emails: {
    $elemMatch: {
      name: "[email protected]"
    }
  }
},
{
  emails: {
    $elemMatch: {
      name: "[email protected]"
    }
  }
})

See the example

Sign up to request clarification or add additional context in comments.

2 Comments

I tried it, doesn't work. It seems my problem is somewhere else than the query, then...
My exact thought. Good tool. :)

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.