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...}
    );

1 Answer 1

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

3 Comments

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?
Np. I don`t think you can do with the regular queries. You may have to use aggregation pipeline. See if this helps stackoverflow.com/questions/15117030/…
Thanks for your help! I will take a look.

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.