Leopold Joy
Leopold Joy

Reputation: 4660

Find documents that contain certain field for sub-object MongoDb and Node.js

I have a collection with the following format:

[ 
  {
     firstname: 'Joe',
     lastname: 'Blow',
     emails: [
       {
          email: '[email protected]',
          valid: false
       },
       {
          email: '[email protected]',
          valid: false
       }
     ],
     password: 'abc123',
     _id: 57017e173915101e0ad5d94a
  },
  {
     firstname: 'Johnny',
     lastname: 'Doe',
     emails: [
       {
          email: '[email protected]',
          valid: false
       }
     ],
     password: 'abc123',
     _id: 57017e173915101e0ad5d87b
  },
]

I am trying to find a user based on the emails.email field. Here is what I have so far:

db.collection('users').aggregate([
    {$unwind: "$emails"},
    {$group: {_id: "$_id",user_emails: { $push: "$emails.email" } } },
    {$match: {'user_emails': { $in: ['[email protected]'] } } }
  ], 
  (error, result) => {
    console.log(error);
    console.log(result);
  }
);

When I run this command in the mongo shell it seems to work; however when I run it in Node.js it prints null for the error and [] for the result.

What am I doing wrong? I am pretty new to MongoDB and just can't seem to figure this out.

Upvotes: 0

Views: 454

Answers (2)

Isaiah4110
Isaiah4110

Reputation: 10080

Why do you want to unwind the entire emails? That will be a very expensive operation when your collection grows with tons of records.

The below query will return the user with the email [email protected]. I think thats what you are looking for right?

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

Upvotes: 2

Saleem
Saleem

Reputation: 8978

I have re-written your code with slight changes.

var col = db.collection('collection');
if (col) {
    col.aggregate([
        {$unwind: "$emails"},
        {$group: {_id: "$_id",user_emails: { $push: "$emails.email" } } },
        {$match: {'user_emails': { $in: ['[email protected]'] } } }
    ], function(e, r){
        if(e){
            console.log(error);
        }

        console.log(r);
        db.close();
    });
}

It should work, provided you have establish connection and other requirements successfully. Provided your sample documents, it will emit:

[
    {
        _id: '57017e173915101e0ad5d94a',
        user_emails: [
            '[email protected]',
            '[email protected]'
        ]
    }
]

Upvotes: 0

Related Questions