0

I'm brand new to MongoDB and Mongoose. I'm currently building an app that has a client collection that contains an array of accounts that the client has.

I'd like to query the collection based on specifics of the accounts the client has. For example, I need to return the client that is:

  • clientType: "Standard"
  • Has two accounts:
    • accountType: "FML", balance: $gt 3000
    • accountType: "OMG", balance: $lt 3000

Below is a sample document:

{
    clientDetails: {
        cardNumber: "0123456",
        firstName: "Bob",
        lastName: "Dole",
        clientType: "Standard"
    },
    accounts: [
        {
            accountNumber: "123",
            accountType: "FML",
            balance: 4000.00
        },
        {
            accountNumber: "234",
            accountType: "OMG",
            balance: 2000
        }
    ]
}

So far, I've only figured out how to build a query that can get a client of clientType "Standard" with accountTypes ["FML","OMG] but I can't figure out how to specify the balance condition for the specific accountTypes.

ClientModel
    .find({
        "clientDetails.clientType": "Standard",
        "accounts.accountType": { $all ["FML", "OMG"]
    })
    .then(
        function(){ //etc..},
        function(err){ //etc...}
    );
chrisk
  • 55
  • 1
  • 4

1 Answers1

2

You can use $all with $elemMatch.

ClientModel
    .find({
        "clientDetails.clientType": "Standard",
        "accounts": 
          { 
             $all: [
                     { "$elemMatch" : { accountType: "FML", balance: { $gt: 3000} } },
                     { "$elemMatch" : { accountType: "OMG", balance: { $lt: 3000} } } 
               ]
          }
    })
    .then(
        function(){ //etc..},
        function(err){ //etc...}
    );
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • this worked great. Thank you! I forgot to mention the client may have many accounts. Is it possible to filter out the accounts that do not match those conditions? – chrisk May 04 '17 at 17:08
  • 1
    Np. I don`t think you can do with the regular queries. You may have to use aggregation pipeline. See if this helps http://stackoverflow.com/questions/15117030/how-to-filter-array-in-subdocument-with-mongodb – s7vr May 04 '17 at 17:12
  • Thanks for your help! I will take a look. – chrisk May 04 '17 at 17:31